# Create your views here.
from django.db.models import Q
import re, json, base64, urllib.parse, os, xlrd
from django.views import View
from Oa_system.models import Staffing
from administrative.models import *
from logistics.MessagePushOperationRecords import RecordAndPush
from supervision_inspection.models import *
from personal_center.models import User
from django.shortcuts import render, redirect, HttpResponse
from datetime import datetime, timedelta
from pypinyin import pinyin, Style
from django.db import connection
from supervision_inspection.switch_data import SwitchData, SwitchDataCopy


# 获取汉字字符串首字母
from supervision_inspection.save_excel_file import SaveExcel


def get_initials(word):
    pinyin_list = pinyin(word, style=Style.NORMAL)
    initials = [p[0][0].upper() for p in pinyin_list if p[0][0].isalpha()]
    return ''.join(initials)


class UploadFileView(View):
    def post(self, request):
        fj_number = request.POST.get("fj_number", "")
        feedback_file = request.FILES.get("file", "")
        file_path = os.path.join(os.getcwd(), f'static/supervision_inspection/feedback_file/{fj_number}')
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        if feedback_file:
            print("文件存放路径为：", file_path)
            new_file_path = os.path.join(file_path, feedback_file.name)
            print("文件存放路径为：", new_file_path)
            with open(new_file_path, "wb") as ff:
                for kk in feedback_file.chunks():
                    ff.write(kk)
        returnDict = {'code': 200, 'message': "上传成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SupervisionInspectionManagement(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        sql = f"""
            SELECT count(id) AS number FROM (
            SELECT A.id FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state='one'
            union all
            SELECT A.id  AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND (B.state in ('two', 'three', 'four', 'five') or B.old_state in ('two', 'three', 'four', 'five'))) base
        """

        sql1 = f"""
            SELECT count(id) AS number FROM (
            SELECT id FROM `supervision_inspection_overdueflow_current_audit_users` WHERE user_id=%(audit_user)s
            union all
            SELECT id FROM `supervision_inspection_deadlinenotification_current_audit_users` WHERE user_id=%(audit_user)s
            union all
            SELECT id FROM `supervision_inspection_deadlinenotification` WHERE NOW()>end_deadline_time AND initiate_or_not='0' AND apply_user_id=%(audit_user)s) base
        """

        sql2 = f"""
            SELECT id FROM `supervision_inspection_departmentperformanceallocation` WHERE assignor_id=%(audit_user)s AND whether_allocate='0'
        """
        with connection.cursor() as cursor:
            cursor.execute(sql, {'audit_user': request.user.id})
            row = cursor.fetchone()

            cursor.execute(sql1, {'audit_user': request.user.id})
            row1 = cursor.fetchone()
            print("==================", row1)
            cursor.execute(sql2, {'audit_user': request.user.id})
            row2 = cursor.fetchone()
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "work_flag": 'true' if row and row[0] else "flase", "overdue_flag": 'true' if row1 and row1[0] else "flase", 'performance_supervision_flag': 'true' if row2 and row2[0] else "flase"}
        return render(request, 'supervision_inspection/supervision_inspection_management.html', context)

class MessageApprovalList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'supervision_inspection/message_approval_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.shortmessageapproval_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='message_approval_draft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='message_approval_detail.html?id={obj.id}'>查看</a> | <a href='message_approval_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state != 'draft'
                      else f"<a href='message_approval_detail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='message_approval_detail.html?id={obj.id}'>查看</a>",
                      'state': obj.get_state_str(), "title": obj.reason}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MessageApprovalIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "uuid": uuid.uuid4()}
        return render(request, 'supervision_inspection/message_approval_index.html', context)

    def post(self, request):
        flow_id = request.POST.get("flow_id", '')
        reason = request.POST.get("reason", '')
        content = request.POST.get("content", '')
        recipient = request.POST.get("recipient", '')
        note = request.POST.get("note", '')
        fj_number = request.POST.get("uuid", '')

        if flow_id:
            obj = ShortMessageApproval.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.content = content
            obj.recipient = recipient
            obj.note = note

            obj.current_audit_users.clear()
            obj.shortmessageapprovalrecord_set.filter(state="unaudit").delete()
            obj.save()
            message = "修改成功！"
        else:
            obj = ShortMessageApproval.objects.create(apply_user=request.user, company=request.user.company, reason=reason, content=content,
                                                      recipient=recipient, note=note, fj_number=fj_number)
            message = "创建成功！"
        flag = True
        one_step = request.user.company.head_people             # 科主任
        if request.user != one_step:
            ShortMessageApprovalRecord.objects.create(parent_id=obj, node="one", audit_people=one_step, audit_note="", state="unaudit")
            obj.current_audit_users.add(one_step)
            obj.state = "one"
            flag = False

        two_step = request.user.company.leaders_id
        ShortMessageApprovalRecord.objects.create(parent_id=obj, node="two", audit_people=two_step, audit_note="", state="unaudit")
        if flag:
            obj.current_audit_users.add(two_step)
            obj.state = "two"

        OfficeObj = User.objects.filter(company_id=80)
        for office in OfficeObj:
            ShortMessageApprovalRecord.objects.create(parent_id=obj, node="three", audit_people=office, audit_note="", state="unaudit")

        obj.save()
        returnDict = {'code': 200, 'message': message}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MessageApprovalDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ShortMessageApproval.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "revise": revise, "file_list": file_list}
        return render(request, 'supervision_inspection/message_approval_draft.html', context)

    def post(self, request):
        flow_id = request.POST.get("flow_id", '')
        reason = request.POST.get("reason", '')
        content = request.POST.get("content", '')
        recipient = request.POST.get("recipient", '')
        note = request.POST.get("note", '')
        fj_number = request.POST.get("uuid", '')

        if flow_id:
            obj = ShortMessageApproval.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.content = content
            obj.recipient = recipient
            obj.note = note
            obj.save()
            message = "修改成功！"
        else:
            obj = ShortMessageApproval.objects.create(apply_user=request.user, company=request.user.company, reason=reason, content=content,
                                                      recipient=recipient, note=note, fj_number=fj_number, state="draft")
            message = "保存成功！"
        returnDict = {'code': 200, 'message': message}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MessageApprovalDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ShortMessageApproval.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.shortmessageapprovalrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.shortmessageapprovalrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                              'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "revise": revise,
                   "file_list": file_list, "audit_dic": audit_dic, "flow_dict": flow_dict,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'supervision_inspection/message_approval_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "短信审批")
        except:
            pass
        obj = ShortMessageApproval.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.shortmessageapprovalrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.shortmessageapprovalrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.shortmessageapprovalrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.shortmessageapprovalrecord_set.filter(node='three', state='unaudit')
                obj_state = 'three'
                for next_audit in next_audit_record:
                    obj.current_audit_users.add(next_audit.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.shortmessageapprovalrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            obj.shortmessageapprovalrecord_set.filter(~Q(audit_people=request.user), node='three', state='unaudit').delete()
            if state == 'audit':
                obj_state = 'end'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class DeleteMessageApproval(View):
    def post(self, request):
        flow_id = request.POST.get("id", "")
        obj = ShortMessageApproval.objects.get(id=int(flow_id))
        obj.current_audit_users.clear()
        obj.audit_users_already.clear()
        obj.shortmessageapprovalrecord_set.all().delete()
        obj.delete()
        returnData = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class SummaryOfficialDocuments(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        DocumentsList = [{"name": "党委会议纪要", "count": 0, "type": "a"}, {"name": "院长办公会会议纪要", "count": 0, "type": "b"}, {"name": "党委会专题会议纪要", "count": 0, "type": "c"},
                         {"name": "院长办公会专题会议纪要", "count": 0, "type": "d"}, {"name": "行政例会简报", "count": 0, "type": "e"}, {"name": "京医发", "count": 0, "type": "f"},
                         {"name": "党委公文", "count": 0, "type": "g"}, {"name": "京医文", "count": 0, "type": "h"}, {"name": "共青团", "count": 0, "type": "i"}]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "DocumentsDict": DocumentsList}
        return render(request, 'supervision_inspection/summary_official_documents.html', context)

    def post(self, request):
        document_type = request.POST.get('document_type', '')
        search_val = request.POST.get('search_val', '')
        page_unmber = request.POST.get('page_unmber', 1)
        file_list = []
        serial = (int(page_unmber) - 1) * 20 + 1
        MemoObj = ConferenceMemo.objects.filter(state="seven", type=document_type)
        for obj in MemoObj[(int(page_unmber) - 1) * 20:int(page_unmber) * 20]:
            file_obj = Topicsattachments.objects.filter(topics_number=obj.number, file_name__contains=search_val)
            for file in file_obj:
                file_list.append({"upload_people": file.uploader_user.real_name, "upload_time": file.create_time.strftime("%Y-%m-%d %H:%M"),
                                  "file_path": file.pdf_path, "dowload_file": str(file.file_path), "file_name": file.file_name, "serial": serial})
                serial += 1

        remainder = MemoObj.count() % 20
        if remainder:
            total_page = int(MemoObj.count() // 20) + 1
        else:
            total_page = int(MemoObj.count() // 20)
        returnData = {'code': 200, 'message': '查询成功！', "file_list": file_list, "total_page": total_page, "total_number": MemoObj.count(), "page_unmber": page_unmber}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class FilePermissions(View):
    def post(self, request):
        PersonnelObj = Staffing.objects.get(station="公文纪要").post_personnel.all()
        if request.user in PersonnelObj:
            flag = "true"
        else:
            flag = "false"
        returnData = {'code': 200, 'message': '查询成功！', "flag": flag}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class CommitteeTopicsList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'supervision_inspection/committee_topics_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.committeetopics_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'date': obj.create_time.strftime("%Y-%m-%d %H:%M"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      'topic_name': obj.topic_name, 'number': obj.number,
                      "url": f"<a href='committee_topics_draft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='committee_topics_detail.html?id={obj.id}'>查看</a> | <a href='committee_topics_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state != 'draft'
                      else f"<a href='committee_topics_detail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='committee_topics_detail.html?id={obj.id}'>查看</a>",
                      'state': obj.get_state_str()}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TopicsApproved(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'supervision_inspection/topics_approved.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = CommitteeTopics.objects.filter(audit_users_already=user).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name, "status": obj.get_state_str(),
                      'date': obj.create_time.strftime("%Y-%m-%d %H:%M"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      'topic_name': obj.topic_name, 'number': obj.number,
                      "url": f"<a href='committee_topics_detail.html?id={obj.id}'>查看</a>"}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class CommitteeTopicsIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        returndata = Company.objects.filter(~Q(id=87)).order_by("serial_number")
        company_list, ComList = [], []
        for c in returndata:
            if c.name not in ComList:
                one_dict = {"id": c.id, "name": c.name}
                company_list.append(one_dict)
                ComList.append(c.name)
        # 专家库
        expert_obj = ExpertDatabase.objects.all().order_by('-create_time')
        # 委员会
        committee_obj = CommitteeTable.objects.all()
        committee_dict = {}
        for ommittee in committee_obj:
            if ommittee.committee_level == "1":
                committee_key = "一级委员会"
            elif ommittee.committee_level == "2":
                committee_key = "二级委员会"
            elif ommittee.committee_level == "3":
                committee_key = "三级委员会"
            elif ommittee.committee_level == "4":
                committee_key = "四级委员会"
            else:
                committee_key = "五级委员会"

            if committee_key not in committee_dict:
                committee_dict[committee_key] = [{"id": ommittee.id, "name": ommittee.committee_name}]
            else:
                committee_dict[committee_key].append({"id": ommittee.id, "name": ommittee.committee_name})
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "uuid": uuid.uuid1(), "company_list": company_list,
                   "expert_obj": expert_obj, "committee_dict": committee_dict}
        return render(request, 'supervision_inspection/committee_topics_index.html', context)
    
    def post(self, request):
        flow_id = request.POST.get("id", "")
        one_step = request.POST.get("one_step", "")
        two_step = request.POST.get('two_step', "")
        three_step = request.POST.get('three_step', "")
        number = request.POST.get("number", "")
        committee_type = request.POST.get('committee_type', "")
        committee = request.POST.get('committee', "")
        expert_database = request.POST.get('expert_database', "")
        topic_name = request.POST.get('topic_name', "")
        committee_name = request.POST.get('committee_name', "")
        dang_xieban = request.POST.get('dang_xieban', "")
        topic_ytnr = request.POST.get('topic_ytnr', "")
        topic_ytyj = request.POST.get('topic_ytyj', "")
        topic_jjfa = request.POST.get('topic_jjfa', "")
        note = request.POST.get('note', "")
        fj_number = request.POST.get('uuid', "")

        organizing_department_list = re.findall('\((.*?)\)', dang_xieban)
        expert_obj = None
        if expert_database != '0':
            expert_obj = ExpertDatabase.objects.get(id=int(expert_database))
        committee_obj = CommitteeTable.objects.get(id=int(committee_name))
        if flow_id:
            obj = CommitteeTopics.objects.get(id=int(flow_id))
            obj.help_department.clear()
            obj.state = "one"
            obj.number = number
            obj.topic_name = topic_name
            obj.expert_database = expert_obj
            obj.committee_type = committee_type
            obj.committee_level = committee
            obj.committee_name = committee_obj
            obj.topic_description = topic_ytnr
            obj.policy_basis = topic_ytyj
            obj.proposed_options = topic_jjfa
            obj.note = note
            for i in organizing_department_list:
                obj.help_department.add(Company.objects.get(id=int(i)))
        else:
            obj = CommitteeTopics.objects.create(state="one", apply_user=request.user, company=request.user.company, number=number, topic_name=topic_name, expert_database=expert_obj,
                                                 committee_type=committee_type, committee_level=committee, committee_name=committee_obj, topic_description=topic_ytnr, policy_basis=topic_ytyj, proposed_options=topic_jjfa,
                                                 note=note, fj_number=fj_number)
            for i in organizing_department_list:
                obj.help_department.add(Company.objects.get(id=int(i)))

        first_step = User.objects.filter(job_number__in=re.findall('\((.*?)\)', one_step))
        second_step = User.objects.filter(job_number__in=re.findall('\((.*?)\)', two_step))
        third_step = User.objects.filter(job_number__in=re.findall('\((.*?)\)', three_step))

        for first in first_step:
            CommitteeTopicsRecord.objects.create(parent_id=obj, node="one", audit_people=first, audit_note="")
            obj.current_audit_users.add(first)

        zero_step = Company.objects.get(id=4).head_people
        CommitteeTopicsRecord.objects.create(parent_id=obj, node="zero", audit_people=zero_step, audit_note="")

        for second in second_step:
            CommitteeTopicsRecord.objects.create(parent_id=obj, node="two", audit_people=second, audit_note="")
        for third in third_step:
            CommitteeTopicsRecord.objects.create(parent_id=obj, node="three", audit_people=third, audit_note="")
        obj.save()

        SequenceObj = Sequence.objects.get(type='-'.join(number.split("-")[:2]), topic_year=datetime.now().strftime("%Y"))
        SequenceObj.sequence = int(SequenceObj.sequence) + 1
        SequenceObj.next_sequence = int(SequenceObj.next_sequence) + 1
        SequenceObj.save()
        returnDict = {'code': 200, 'message': "创建成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class CommitteeTopicsDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = CommitteeTopics.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.committeetopicsrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime(
                        "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                 audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.committeetopicsrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime(
                        "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                 audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        # 专家库
        expert_obj = ExpertDatabase.objects.all().order_by('-create_time')
        # 委员会
        committee_obj = CommitteeTable.objects.all()
        committee_dict = {}
        for ommittee in committee_obj:
            if ommittee.committee_level == "1":
                committee_key = "一级委员会"
            elif ommittee.committee_level == "2":
                committee_key = "二级委员会"
            elif ommittee.committee_level == "3":
                committee_key = "三级委员会"
            elif ommittee.committee_level == "4":
                committee_key = "四级委员会"
            else:
                committee_key = "五级委员会"

            if committee_key not in committee_dict:
                committee_dict[committee_key] = [{"id": ommittee.id, "name": ommittee.committee_name}]
            else:
                committee_dict[committee_key].append({"id": ommittee.id, "name": ommittee.committee_name})
        returndata = Company.objects.filter(~Q(id=87)).order_by("serial_number")
        company_list, ComList = [], []
        for c in returndata:
            if c.name not in ComList:
                one_dict = {"id": c.id, "name": c.name}
                company_list.append(one_dict)
                ComList.append(c.name)
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "revise": revise,
                   "organizing_department": ", ".join([f"{i.name}{i.id}" for i in obj.help_department.all()]), "file_list": file_list, "expert_obj": expert_obj, "committee_dict": committee_dict,
                   'topic_description': urllib.parse.unquote(base64.b64decode(obj.topic_description).decode()), "company_list": company_list,
                   'policy_basis': urllib.parse.unquote(base64.b64decode(obj.policy_basis).decode()),
                   'proposed_options': urllib.parse.unquote(base64.b64decode(obj.proposed_options).decode()) if obj.proposed_options != "空" else "",
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'supervision_inspection/committee_topics_draft.html', context)

    def post(self, request):
        flow_id = request.POST.get("id", "")
        committee_type = request.POST.get('committee_type', "")
        committee = request.POST.get('committee', "")
        expert_database = request.POST.get('expert_database', "")
        topic_name = request.POST.get('topic_name', "")
        committee_name = request.POST.get('committee_name', "")
        dang_xieban = request.POST.get('dang_xieban', "")
        topic_ytnr = request.POST.get('topic_ytnr', "")
        topic_ytyj = request.POST.get('topic_ytyj', "")
        topic_jjfa = request.POST.get('topic_jjfa', "")
        note = request.POST.get('note', "")
        fj_number = request.POST.get('uuid', "")

        organizing_department_list = re.findall('\((.*?)\)', dang_xieban)
        try:
            if expert_database != "0":
                expert_obj = ExpertDatabase.objects.get(id=int(expert_database))
            else:
                expert_obj = ""
        except:
            expert_obj = ""
        try:
            if committee_name != "0":
                committee_obj = CommitteeTable.objects.get(id=int(committee_name))
            else:
                committee_obj = ""
        except:
            committee_obj = ""
        if flow_id:
            obj = CommitteeTopics.objects.get(id=int(flow_id))
            obj.help_department.clear()
            obj.state = "draft"
            obj.topic_name = topic_name
            if expert_obj:
                obj.expert_database = expert_obj
            if committee_type:
                obj.committee_type = committee_type
            obj.committee_level = committee
            if committee_obj:
                obj.committee_name = committee_obj
            obj.topic_description = topic_ytnr
            obj.policy_basis = topic_ytyj
            obj.proposed_options = topic_jjfa
            obj.note = note
            for i in organizing_department_list:
                obj.help_department.add(Company.objects.get(id=int(i)))
        else:
            obj = CommitteeTopics.objects.create(state="draft", apply_user=request.user, company=request.user.company, topic_name=topic_name,
                                                 committee_type=committee_type, topic_description=topic_ytnr, policy_basis=topic_ytyj, proposed_options=topic_jjfa,
                                                 note=note, fj_number=fj_number)
            for i in organizing_department_list:
                obj.help_department.add(Company.objects.get(id=int(i)))
        obj.save()
        returnDict = {'code': 200, 'message': "保存成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class CommitteeTopicsDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = CommitteeTopics.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.committeetopicsrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.committeetopicsrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "revise": revise, "organizing_department": ", ".join([i.name for i in obj.help_department.all()]),
                   "file_list": file_list, "audit_dic": audit_dic, "flow_dict": flow_dict,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['zero', 'one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['zero', 'one', 'two', 'three'] and request.user == obj.apply_user else 'false',
                   'topic_description': urllib.parse.unquote(base64.b64decode(obj.topic_description).decode()),
                   'policy_basis': urllib.parse.unquote(base64.b64decode(obj.policy_basis).decode()),
                   'proposed_options': urllib.parse.unquote(base64.b64decode(obj.proposed_options).decode()) if obj.proposed_options != "空" else "",
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'supervision_inspection/committee_topics_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "委员会议题审核")
        except:
            pass
        obj = CommitteeTopics.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.remove(request.user)

        if obj.state == 'zero':
            audit_record = obj.committeetopicsrecord_set.filter(node='zero', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if not obj.current_audit_users.all().count():
                    next_audit_record = obj.committeetopicsrecord_set.filter(node='two', state='unaudit')
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                    obj_state = 'two'
                else:
                    obj_state = 'zero'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'one':
            audit_record = obj.committeetopicsrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if not obj.current_audit_users.all().count():
                    next_audit_record = obj.committeetopicsrecord_set.filter(node='zero', state='unaudit')
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                    obj_state = 'zero'
                else:
                    obj_state = 'one'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.committeetopicsrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if not obj.current_audit_users.all().count():
                    next_audit_record = obj.committeetopicsrecord_set.filter(node='three', state='unaudit')
                    obj_state = 'three'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                else:
                    obj_state = 'two'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.committeetopicsrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if not obj.current_audit_users.all().count():
                    obj_state = 'unmetting'
                else:
                    obj_state = 'three'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class CommitteeTopicsMmodify(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = CommitteeTopics.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.committeetopicsrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.committeetopicsrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        returndata = Company.objects.filter(~Q(id=87)).order_by("serial_number")
        company_list, ComList = [], []
        for c in returndata:
            if c.name not in ComList:
                one_dict = {"id": c.id, "name": c.name}
                company_list.append(one_dict)
                ComList.append(c.name)
        # 专家库
        expert_obj = ExpertDatabase.objects.all().order_by('-create_time')
        # 委员会
        committee_obj = CommitteeTable.objects.all()
        committee_dict = {}
        for ommittee in committee_obj:
            if ommittee.committee_level == "1":
                committee_key = "一级委员会"
            elif ommittee.committee_level == "2":
                committee_key = "二级委员会"
            elif ommittee.committee_level == "3":
                committee_key = "三级委员会"
            elif ommittee.committee_level == "4":
                committee_key = "四级委员会"
            else:
                committee_key = "五级委员会"

            if committee_key not in committee_dict:
                committee_dict[committee_key] = [{"id": ommittee.id, "name": ommittee.committee_name}]
            else:
                committee_dict[committee_key].append({"id": ommittee.id, "name": ommittee.committee_name})
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "revise": revise, "organizing_department": ", ".join([f"{i.name}({i.id})" for i in obj.help_department.all()]),
                   "file_list": file_list, "audit_dic": audit_dic, "flow_dict": flow_dict, "company_list": company_list, "committee_dict": committee_dict,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false', "expert_obj": expert_obj,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three'] and request.user == obj.apply_user else 'false',
                   'topic_description': urllib.parse.unquote(base64.b64decode(obj.topic_description).decode()),
                   'policy_basis': urllib.parse.unquote(base64.b64decode(obj.policy_basis).decode()),
                   'proposed_options': urllib.parse.unquote(base64.b64decode(obj.proposed_options).decode()) if obj.proposed_options != "空" else "",
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'supervision_inspection/committee_topics_modify.html', context)

    def post(self, request):
        flow_id = request.POST.get("id", "")
        one_step = request.POST.get("one_step", "")
        two_step = request.POST.get('two_step', "")
        three_step = request.POST.get('three_step', "")
        expert_database = request.POST.get('expert_database', "")   #
        topic_name = request.POST.get('topic_name', "")         #
        dang_xieban = request.POST.get('dang_xieban', "")       #
        topic_ytnr = request.POST.get('topic_ytnr', "")
        topic_ytyj = request.POST.get('topic_ytyj', "")
        topic_jjfa = request.POST.get('topic_jjfa', "")
        note = request.POST.get('note', "")

        organizing_department_list = re.findall('\((.*?)\)', dang_xieban)
        expert_obj = ExpertDatabase.objects.get(id=int(expert_database))

        obj = CommitteeTopics.objects.get(id=int(flow_id))
        obj.current_audit_users.clear()
        obj.committeetopicsrecord_set.filter(state='unaudit').delete()
        obj.help_department.clear()
        obj.state = "one"
        obj.topic_name = topic_name
        obj.expert_database = expert_obj
        obj.topic_description = topic_ytnr
        obj.policy_basis = topic_ytyj
        obj.proposed_options = topic_jjfa
        obj.note = note
        for i in organizing_department_list:
            obj.help_department.add(Company.objects.get(id=int(i)))

        first_step = User.objects.filter(job_number__in=re.findall('\((.*?)\)', one_step))
        second_step = User.objects.filter(job_number__in=re.findall('\((.*?)\)', two_step))
        third_step = User.objects.filter(job_number__in=re.findall('\((.*?)\)', three_step))
        
        for first in first_step:
            CommitteeTopicsRecord.objects.create(parent_id=obj, node="one", audit_people=first, audit_note="")
            obj.current_audit_users.add(first)
        for second in second_step:
            CommitteeTopicsRecord.objects.create(parent_id=obj, node="two", audit_people=second, audit_note="")
        for third in third_step:
            CommitteeTopicsRecord.objects.create(parent_id=obj, node="three", audit_people=third, audit_note="")
        obj.save()
        returnDict = {'code': 200, 'message': "修改成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ListOfIssues(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        LeftNavigation = {}
        committee_obj = CommitteeTable.objects.all()
        for ommittee in committee_obj:
            if ommittee.committee_level == "1":
                committee_key = "一级委员会"
                NavKey = "first_key"
            elif ommittee.committee_level == "2":
                committee_key = "二级委员会"
                NavKey = "two_key"
            elif ommittee.committee_level == "3":
                committee_key = "三级委员会"
                NavKey = "three_key"
            elif ommittee.committee_level == "4":
                committee_key = "四级委员会"
                NavKey = "four_key"
            else:
                committee_key = "五级委员会"
                NavKey = "five_key"

            if committee_key not in LeftNavigation:
                LeftNavigation[committee_key] = {}
                LeftNavigation[committee_key]["key"] = NavKey
                LeftNavigation[committee_key]["date"] = [{"id": ommittee.id, "name": ommittee.committee_name}]
            else:
                LeftNavigation[committee_key]["date"].append({"id": ommittee.id, "name": ommittee.committee_name})
        leader_obj = User.objects.filter(group__in=[1, 2])
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "LeftNavigation": LeftNavigation, "leader_obj": leader_obj}
        return render(request, 'supervision_inspection/list_of_Issues.html', context)

    def post(self, request):
        committee_id = request.POST.get("committee_id", "")
        obj = CommitteeTopics.objects.filter(committee_name__id=int(committee_id), state="unmetting")
        search_data = []
        serial = 1
        for i in obj:
            search_data.append({
                "serial": serial, "id": i.id, "topic_name": i.topic_name, "number": i.number, "apply_user": i.apply_user.real_name,
                "create_time": i.create_time.strftime("%Y-%m-%d %H:%M"), "appove_time": i.committeetopicsrecord_set.all().order_by("update_time").last().update_time.strftime("%Y-%m-%d %H:%M")
            })
            serial += 1
        returnDict = {'code': 200, 'message': "查询成功！", "data": search_data}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TheAgendaMeeting(View):
    def post(self, request):
        meeting_time = request.POST.get("meeting_time", "")                     # 开会时间
        id_list = request.POST.get("id_list", "")  # 上会议题ID列表
        ConferenceHost = request.POST.get("ConferenceHost", "")                 # 主持人
        create_flag = True
        for i in json.loads(id_list):
            obj = CommitteeTopics.objects.get(id=int(i))
            obj.state = "metting"
            obj.save()

            aaa_obj = AttendedMeeting.objects.filter(committee_name=obj.committee_name)
            obj_number = int(aaa_obj.first().number) + 1 if aaa_obj.count() else 1

            AttendedMeeting.objects.create(topic=obj, committee_name=obj.committee_name, meet_time=meeting_time, compere=User.objects.get(id=int(ConferenceHost)), number=obj_number)
            if create_flag and obj.expert_database:
                for k in obj.expert_database.expertpeople_set.all():
                    CommitteeAttendance.objects.create(committee_name=obj.committee_name, number=obj.number, signee=k.name)
                create_flag = False
        returnDict = {'code': 200, 'message': "上会成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class CommitteeVotingTopics(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        obj = AttendedMeeting.objects.filter(status="progress")
        if obj:
            left_nav = []
            Serial = 1
            for i in obj:
                left_nav.append({"id": i.committee_name.id, "name": i.committee_name.committee_name})
                Serial += 1
            meeting_name = obj.first().committee_name.committee_name
            meet_obj = AttendedMeeting.objects.filter(status="progress", committee_name=obj.first().committee_name)
            meet_list = []
            Serial = 1
            for j in meet_obj:
                meet_list.append({"id": j.topic.id, "topic_name": j.topic.topic_name, "Serial": Serial, "number": j.topic.number, "apply_user": j.topic.apply_user.real_name,
                                  "create_time": j.topic.create_time.strftime("%Y-%m-%d %H:%M"), "state": j.state})
                Serial += 1

            liaison_obj = "false"
            if request.user == obj.first().committee_name.liaison_officer:
                liaison_obj = "true"

            meet_number = obj.first().number

            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "left_nav": left_nav, "meeting_name": meeting_name,
                       "meet_list": meet_list, "liaison_obj": liaison_obj, "meet_number": meet_number}
            return render(request, 'supervision_inspection/committee_voting_topics.html', context)
        else:
            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                       "left_nav": [], "meeting_name": "",
                       "meet_list": [], "liaison_obj": "false", "meet_number": ""}
            return render(request, 'supervision_inspection/committee_voting_topics.html', context)

    def post(self, request):
        meeting_name = request.POST.get("meeting_name", None)
        meet_number = request.POST.get("meet_number", None)
        types = request.POST.get("types", None)

        topic_obj = AttendedMeeting.objects.filter(committee_name__committee_name=meeting_name, number=str(meet_number))
        if types == 'start':
            for top_obj in topic_obj:
                top_obj.state = 'voting'
                top_obj.save()
        else:
            for top_obj in topic_obj:
                top_obj.status = 'ending'
                top_obj.save()

        returnDict = {'code': 200, 'message': '', "types": types.strip()}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TopicVotingDetails(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        vote_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = CommitteeTopics.objects.get(id=int(vote_id))
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.committeetopicsrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.committeetopicsrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        all_people = AttendedMeeting.objects.get(topic=obj).attendedmeetingpeople_set.all()
        all_list = [{
            "real_name": i.leaders,
            "vote_reluse": "未投票" if i.state == "voting" else "同意" if i.state == "agree" else "反对" if i.state == "opposition" else "弃权",
            "vote_node": i.node, "vote_time": i.update_time.strftime("%Y-%m-%d %H:%M") if i.state != "voting" else "",
        } for i in all_people]

        UpperNextDict = {}

        ThePrevious = AttendedMeeting.objects.filter(committee_name=obj.committee_name, number=obj.number, id__lt=int(vote_id)).order_by("-id")
        if ThePrevious:
            UpperNextDict['upper'] = {'obj': ThePrevious.first(), "status": 'true'}
        else:
            UpperNextDict['upper'] = {'obj': '', "status": 'false'}

        NextPrevious = AttendedMeeting.objects.filter(committee_name=obj.committee_name, number=obj.number, id__gt=int(vote_id)).order_by("id")
        if NextPrevious:
            UpperNextDict['next'] = {'obj': NextPrevious.first(), "status": 'true'}
        else:
            UpperNextDict['next'] = {'obj': '', "status": 'false'}
        host_people = AttendedMeeting.objects.get(topic=obj).compere.real_name

        AttendedObj = AttendedMeeting.objects.get(topic=obj)
        all_people_count = all_people.count()  # 参与投票的总人数
        meet_leaders = CommitteeAttendance.objects.filter(committee_name=AttendedObj.committee_name, number=AttendedObj.number).count()
        VotersNumber = AttendedObj.attendedmeetingpeople_set.filter(state__in=['agree', 'opposition', 'waiver']).count()  # 已投票人数

        try:
            jjj_obj = AttendedMeeting.objects.get(topic=obj)
            if jjj_obj.status == "ending":
                top_flag = "false"
                modify = "false"
                my_state, my_node = '', ''
            else:
                if jjj_obj.state != "notstart":
                    my_obj = jjj_obj.attendedmeetingpeople_set.filter(leaders=request.user.real_name)
                    my_state = my_obj.first().state
                    my_node = my_obj.first().node
                    if my_state == "voting":
                        top_flag = "true"
                    else:
                        top_flag = "false"

                    if my_state != 'voting':
                        modify = "true"
                    else:
                        modify = "false"
                else:
                    top_flag = "false"
                    modify = "false"
                    my_state, my_node = '', ''
        except:
            top_flag = "false"
            modify = "false"
            my_state, my_node = '', ''

        UpperNextDict = {"upper": {}, "next": {}}
        try:
            upper_obj = AttendedMeeting.objects.filter(id__lt=AttendedObj.id, topic_year=AttendedObj.topic_year, number=AttendedObj.number).order_by("-id").first()
            UpperNextDict["upper"]["status"] = 'true'
            UpperNextDict["upper"]["topic_id"] = upper_obj.topic.id
            UpperNextDict["upper"]["topics_name"] = upper_obj.topic.topic_name
        except:
            UpperNextDict["upper"]["status"] = 'false'
            UpperNextDict["upper"]["topic_id"] = ""
            UpperNextDict["upper"]["topics_name"] = ""

        try:
            next_obj = AttendedMeeting.objects.filter(id__gt=AttendedObj.id, topic_year=AttendedObj.topic_year, number=AttendedObj.number).order_by("id").first()
            UpperNextDict["next"]["status"] = 'true'
            UpperNextDict["next"]["topic_id"] = next_obj.topic.id
            UpperNextDict["next"]["topics_name"] = next_obj.topic.topic_name
        except:
            UpperNextDict["next"]["status"] = 'false'
            UpperNextDict["next"]["topic_id"] = ""
            UpperNextDict["next"]["topics_name"] = ""

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "all_list": all_list,
                   "obj": obj, "revise": revise, "organizing_department": ", ".join([i.name for i in obj.help_department.all()]),
                   "file_list": file_list, "audit_dic": audit_dic, "flow_dict": flow_dict, "UpperNextDict": UpperNextDict,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three'] and request.user == obj.apply_user else 'false',
                   'topic_description': urllib.parse.unquote(base64.b64decode(obj.topic_description).decode()), "my_node": my_node,
                   'policy_basis': urllib.parse.unquote(base64.b64decode(obj.policy_basis).decode()), "host_people": host_people,
                   'proposed_options': urllib.parse.unquote(base64.b64decode(obj.proposed_options).decode()) if obj.proposed_options != "空" else "",
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   'meet_leaders': meet_leaders, "VotersNumber": VotersNumber, "all_people_count": all_people_count, "top_flag": top_flag, "modify": modify, "my_state": my_state
                   }
        return render(request, 'supervision_inspection/topic_voting_details.html', context)

    def post(self, request):
        vote_node = request.POST.get("vote_node", None)  # 投票意见
        vote_reluse = request.POST.get("vote_reluse", None)  # 投票结果
        topic_id = request.POST.get("topic_id", None)  # 投票表对应的ID
        # try:
        Topic_Obj = CommitteeTopics.objects.get(id=int(topic_id))

        AttendedObj = AttendedMeeting.objects.get(topic=Topic_Obj)
        if AttendedObj.state == 'notstart':
            returnDict = {'status': 'success', "code": 400, "msg": "对不起！会议还未开始，请耐心等待!"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        topicObj = AttendedMeetingPeople.objects.get(leaders=request.user.real_name, topics_id=AttendedObj)

        topicObj.update_time = datetime.now()
        topicObj.state = vote_reluse
        topicObj.node = vote_node
        topicObj.save()

        if not AttendedMeetingPeople.objects.filter(state="voting", topics_id=AttendedObj).count():
            agree_obj = AttendedMeetingPeople.objects.filter(state="agree", topics_id=AttendedObj).count()
            all_obj = AttendedMeetingPeople.objects.filter(topics_id=AttendedObj).count()
            if (agree_obj / all_obj) >= 2/3:
                AttendedObj.state = "adopt"
            else:
                AttendedObj.state = "nopass"
        AttendedObj.save()
        returnDict = {'status': 'success', "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SummaryOfIssues(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        CommitteeObj = CommitteeTable.objects.all()
        data_dict = {}
        for i in CommitteeObj:
            if i.committee_level == '1':
                fist_key = "一级委员会"
                if fist_key not in data_dict:
                    data_dict[fist_key] = {i.committee_name: {"id": i.id, "meet_list": []}}
                else:
                    if i.committee_name not in data_dict[fist_key]:
                        data_dict[fist_key] = {i.committee_name: {"id": i.id, "meet_list": []}}
            elif i.committee_level == '2':
                fist_key = "二级委员会"
                if fist_key not in data_dict:
                    data_dict[fist_key] = {i.committee_name: {"id": i.id, "meet_list": []}}
                else:
                    if i.committee_name not in data_dict[fist_key]:
                        data_dict[fist_key] = {i.committee_name: {"id": i.id, "meet_list": []}}
            elif i.committee_level == '3':
                fist_key = "三级委员会"
                if fist_key not in data_dict:
                    data_dict[fist_key] = {i.committee_name: {"id": i.id, "meet_list": []}}
                else:
                    if i.committee_name not in data_dict[fist_key]:
                        data_dict[fist_key] = {i.committee_name: {"id": i.id, "meet_list": []}}
            elif i.committee_level == '4':
                fist_key = "四级委员会"
                if fist_key not in data_dict:
                    data_dict[fist_key] = {i.committee_name: {"id": i.id, "meet_list": []}}
                else:
                    if i.committee_name not in data_dict[fist_key]:
                        data_dict[fist_key] = {i.committee_name: {"id": i.id, "meet_list": []}}
            else:
                fist_key = "五级委员会"
                if fist_key not in data_dict:
                    data_dict[fist_key] = {i.committee_name: {"id": i.id, "meet_list": []}}
                else:
                    if i.committee_name not in data_dict[fist_key]:
                        data_dict[fist_key] = {i.committee_name: {"id": i.id, "meet_list": []}}

            meet_obj = AttendedMeeting.objects.filter(committee_name=i)
            for t in meet_obj:
                neet_name = f"{t.topic_year}年第{t.number}次{i.committee_name}"
                if neet_name not in data_dict[fist_key][i.committee_name]["meet_list"]:
                    data_dict[fist_key][i.committee_name]["meet_list"].append(neet_name)
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "data_dict": data_dict}
        return render(request, 'supervision_inspection/summary_of_issues.html', context)

    def post(self, request):
        meet_name = request.POST.get("meet_name", '')
        meet_year = re.findall("(.*?)年", meet_name)[0]
        meet_number = re.findall("第(.*?)次", meet_name)[0]
        obj = AttendedMeeting.objects.filter(topic_year=meet_year, number=meet_number)
        serial, data_list = 1, []
        for i in obj:
            if i.status == 'ending' and i.state == 'notstart':
                flow_state = "完结"
            else:
                if i.state == 'notstart':
                   flow_state = "未开始"
                elif i.state == 'nopass':
                   flow_state = '<span style="color: red;">未通过</span>'
                elif i.state == 'suspension':
                   flow_state = '<span style="color: red;">暂缓</span>'
                elif i.state == 'adopt':
                   flow_state = '<span style="color: limegreen;">通过</span>'
                else:
                   flow_state = "投票中"
            data_list.append({"serial": serial, "topic_name": i.topic.topic_name, "number": i.topic.number, "apply_user": i.topic.apply_user.real_name,
                              "create_time": i.topic.create_time.strftime("%Y-%m-%d %H:%M"), "id": i.topic.id, "state": flow_state})
            serial += 1
        returnDict = {'status': 'success', "code": 200, "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MyDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'supervision_inspection/my_draft.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = CommitteeMinutes.objects.filter(apply_user=request.user).order_by('-create_time')
        data_list = [{'id': obj.id,
                      "conference_memo_text": obj.conference_memo_text,
                      'number': obj.document_number,
                      'drafter': obj.drafter,
                      'drafter_company': obj.drafter_company,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='summary_application_draft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='summary_application_detail.html?id={obj.id}'>查看</a> | <a href='summary_application_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state in ['zero', 'one', 'two', 'three']
                      else f"<a href='summary_application_detail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='summary_application_detail.html?id={obj.id}'>查看</a>",
                      'state': obj.get_state_str()}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MyApproved(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'supervision_inspection/my_approved.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = CommitteeMinutes.objects.filter(audit_users_already=request.user).order_by('-create_time')
        data_list = [{'id': obj.id,
                      "conference_memo_text": obj.conference_memo_text,
                      'number': obj.document_number,
                      'drafter': obj.drafter,
                      'drafter_company': obj.drafter_company,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='summary_application_detail.html?id={obj.id}'>查看</a>",
                      'state': obj.get_state_str()}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DeleteFlow(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        objs = CommitteeMinutes.objects.get(id=int(flow_id))
        objs.current_audit_users.clear()
        objs.audit_users_already.clear()
        objs.committeeminutesrecord_set.all().delete()
        objs.delete()
        returnData = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class SummaryApplicationIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        CompanyList = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in CompanyList:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        now_time = datetime.now().strftime("%Y")
        try:
            a = Sequence.objects.get(type='WYHJY', topic_year=now_time)
            a_next_sequence = a.next_sequence
        except Exception as a:
            a = Sequence.objects.create(type='WYHJY', sequence='0', next_sequence='1', topic_year=now_time)
            a_next_sequence = '1'
            a.save()
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "company_list": company_list,
                   "a_next_sequence": a_next_sequence, "now_time": now_time, "uuid": uuid.uuid4()}
        return render(request, 'supervision_inspection/summary_application_index.html', context)

    def post(self, request):
        flow_id = request.POST.get("id", '')
        OfficeReviewer = request.POST.get("OfficeReviewer", '')
        CountersignReviewer = request.POST.get("CountersignReviewer", '')
        IssuanceReviewer = request.POST.get("IssuanceReviewer", '')
        document_number = request.POST.get("document_number", '')
        drafting_department = request.POST.get("drafting_department", '')
        drafted_by = request.POST.get("drafted_by", '')
        conference_memo_text = request.POST.get("conference_memo_text", '')
        main_company = request.POST.get("main_company", '')
        vice_company = request.POST.get("vice_company", '')
        servings = request.POST.get("servings", '')
        fj_number = request.POST.get("uuid", '')
        if flow_id:
            obj = CommitteeMinutes.objects.get(id=int(flow_id))
            obj.document_number = document_number
            obj.fj_number = fj_number
            obj.drafter = drafted_by
            obj.drafter_company = drafting_department
            obj.main_company = main_company
            obj.vice_company = vice_company
            obj.servings = servings
            obj.conference_memo_text = conference_memo_text
            obj.current_audit_users.clear()
            obj.committeeminutesrecord_set.filter(state='unaudit').delete()
        else:
            obj = CommitteeMinutes.objects.create(apply_user=request.user, fj_number=fj_number, drafter=drafted_by, drafter_company=drafting_department, document_number=document_number,
                                            document_year=datetime.now().year, main_company=main_company, vice_company=vice_company, servings=servings, conference_memo_text=conference_memo_text)

        office_reviewer = re.findall('\((.*?)\)', OfficeReviewer)
        for office in office_reviewer:
            audit_people = User.objects.get(job_number=office)
            CommitteeMinutesRecord.objects.create(parent_id=obj, audit_people=audit_people, audit_note="", node="one")
            obj.current_audit_users.add(audit_people)

        zero_step = Company.objects.get(id=4).head_people
        CommitteeMinutesRecord.objects.create(parent_id=obj, node="zero", audit_people=zero_step, audit_note="")

        countersign_reviewer = re.findall('\((.*?)\)', CountersignReviewer)
        for countersign in countersign_reviewer:
            CommitteeMinutesRecord.objects.create(parent_id=obj, audit_people=User.objects.get(job_number=countersign), audit_note="", node="two")

        issuance_reviewer = re.findall('\((.*?)\)', IssuanceReviewer)
        for issuance in issuance_reviewer:
            CommitteeMinutesRecord.objects.create(parent_id=obj, audit_people=User.objects.get(job_number=issuance), audit_note="", node="three")

        now_time = datetime.now().strftime("%Y")
        try:
            a = Sequence.objects.get(type='WYHJY', topic_year=now_time)
        except Exception as a:
            a = Sequence.objects.create(type='WYHJY', sequence='0', next_sequence='1', topic_year=now_time)
        a.sequence = int(a.sequence) + 1
        a.next_sequence = int(a.next_sequence) + 1
        a.save()

        obj.state = 'one'
        obj.save()
        returnDict = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SummaryApplicationDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = CommitteeMinutes.objects.get(id=id)
        CompanyList = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in CompanyList:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        now_time = datetime.now().strftime("%Y")
        try:
            a = Sequence.objects.get(type='WYHJY', topic_year=now_time)
            a_next_sequence = a.next_sequence
        except Exception as a:
            a = Sequence.objects.create(type='WYHJY', sequence='0', next_sequence='1', topic_year=now_time)
            a_next_sequence = '1'
            a.save()
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "revise": revise, "file_list": file_list,
                   "a_next_sequence": a_next_sequence, "now_time": now_time, "company_list": company_list}
        return render(request, 'supervision_inspection/summary_application_draft.html', context)

    def post(self, request):
        flow_id = request.POST.get("id", '')
        document_number = request.POST.get("document_number", '')
        drafting_department = request.POST.get("drafting_department", '')
        drafted_by = request.POST.get("drafted_by", '')
        conference_memo_text = request.POST.get("conference_memo_text", '')
        main_company = request.POST.get("main_company", '')
        vice_company = request.POST.get("vice_company", '')
        servings = request.POST.get("servings", '')
        fj_number = request.POST.get("uuid", '')

        if flow_id:
            obj = CommitteeMinutes.objects.get(id=int(flow_id))
            obj.document_number = document_number
            obj.drafter = drafted_by
            obj.drafter_company = drafting_department
            obj.main_company = main_company
            obj.vice_company = vice_company
            obj.servings = servings
            obj.conference_memo_text = conference_memo_text
            obj.save()
        else:
            obj = CommitteeMinutes.objects.create(apply_user=request.user, fj_number=fj_number, drafter=drafted_by, drafter_company=drafting_department, document_number=document_number,
                                                  document_year=datetime.now().year, main_company=main_company, vice_company=vice_company, servings=servings, conference_memo_text=conference_memo_text)
        obj.state = "draft"
        obj.save()
        returnDict = {'code': 200, 'message': "保存成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SummaryApplicationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = CommitteeMinutes.objects.get(id=id)
        bute_obj = CommitteeMinutesPeople.objects.filter(parent_id=obj, audit_people=request.user)
        if bute_obj.count():
            for bute in bute_obj:
                bute.state = "accepted"
                bute.update_time = datetime.now()
                bute.save()
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        audit_dic, flow_dict, approve_people_num, approval_details = {}, {}, 0, []
        for audit_obj in obj.committeeminutesrecord_set.all():
            approve_people_num += 1
            approval_details.append({
                'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                 'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                 'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                 'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''
            })

            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.committeeminutesrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        distribute_obj = CommitteeMinutesPeople.objects.filter(parent_id=obj)
        read_number, unread_number, read_list, unread_list, all_list = 0, 0, [], [], []
        for dis in distribute_obj:
            one_dict = {"name": dis.audit_people.real_name, "status": "未收阅" if dis.state == "accept" else "已收阅",
                        "time": "" if dis.state == "accept" else dis.update_time.strftime("%Y-%m-%d %H:%M"),
                        "signature_picture": "" if dis.state == "accept" else ('/media/' + str(dis.audit_people.signature_picture))}
            all_list.append(one_dict)
            if dis.state == "accept":           # 未读
                unread_list.append(one_dict)
                unread_number += 1
            else:
                read_list.append(one_dict)
                read_number += 1

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "revise": revise, "read_list": read_list, "unread_list": unread_list,
                   "file_list": file_list, "audit_dic": audit_dic, "flow_dict": flow_dict, "approve_people_num": approve_people_num, "approval_details": approval_details, "all_list": all_list,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false', "total_number": distribute_obj.count(),
                   'is_audit': 'true' if obj.state in ['zero', 'one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false', "read_number": read_number,
                   'is_stop': 'true' if obj.state in ['zero', 'one', 'two', 'three', 'refuse'] and request.user == obj.apply_user else 'false', "unread_number": unread_number,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""}
        return render(request, 'supervision_inspection/summary_application_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "委员会纪要")
        except:
            pass
        obj = CommitteeMinutes.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.remove(request.user)
        if obj.state == 'zero':
            audit_record = obj.committeeminutesrecord_set.filter(node='zero', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.current_audit_users.all().count():
                    obj_state = 'zero'
                else:
                    obj_state = 'two'
                    next_audit_record = obj.committeeminutesrecord_set.filter(node='two', state='unaudit')
                    for one_step in next_audit_record:
                        obj.current_audit_users.add(one_step.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'one':
            audit_record = obj.committeeminutesrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.current_audit_users.all().count():
                    obj_state = 'one'
                else:
                    obj_state = 'zero'
                    next_audit_record = obj.committeeminutesrecord_set.filter(node='zero', state='unaudit')
                    for one_step in next_audit_record:
                        obj.current_audit_users.add(one_step.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.committeeminutesrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.current_audit_users.all().count():
                    obj_state = 'two'
                else:
                    obj_state = 'three'
                    next_audit_record = obj.committeeminutesrecord_set.filter(node='three', state='unaudit')
                    for two_step in next_audit_record:
                        obj.current_audit_users.add(two_step.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.committeeminutesrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.current_audit_users.all().count():
                    obj_state = 'three'
                else:
                    obj_state = 'four'
                    obj.current_audit_users.add(obj.apply_user)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            prople_list = request.POST.get('prople_list', [])
            for people in json.loads(prople_list):
                CommitteeMinutesPeople.objects.create(parent_id=obj, audit_people=User.objects.get(job_number=re.findall('\((.*?)\)', people)[0]))
            obj.state = "end"
            obj.can_revise = '0'
            obj.save()
            returnDict = {'code': 200, 'message': '分发成功！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class SummaryApplicationStop(View):
    def post(self, request):
        id = request.POST.get('id', None)
        types = request.POST.get('types', 'stop')  # stop 终止 delete 删除
        if types == 'stop':
            obj = CommitteeMinutes.objects.get(id=int(id))
            if obj.state == 'end':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的流程不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
                returnData = {'code': 200, 'message': '终止成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            obj = CommitteeMinutes.objects.get(id=int(id))
            obj.current_audit_users.clear()
            obj.committeeminutesrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

class GetCommitteeTopicsNumber(View):
    def post(self, request):
        committee = request.POST.get("committee", "")
        obj = CommitteeTable.objects.get(id=int(committee))
        Initial = get_initials(obj.committee_name)
        try:
            number_obj = Sequence.objects.get(type=f"JY-{Initial}", topic_year=datetime.now().year)
            number = number_obj.next_sequence
        except:
            number = 1
            Sequence.objects.create(type=f"JY-{Initial}", topic_year=datetime.now().year, sequence=0, next_sequence=1)
        topic_number = f"JY-{Initial}-{datetime.now().year}-{number}"

        returnData = {'code': 200, 'message': '查询成功！', "topic_number": topic_number}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class DeleteCommitteeTopics(View):
    def post(self, request):
        flow_id = request.POST.get("id", "")
        obj = CommitteeTopics.objects.get(id=int(flow_id))
        obj.current_audit_users.clear()
        obj.audit_users_already.clear()
        obj.committeetopicsrecord_set.all().delete()
        obj.delete()
        returnData = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ProcessModificationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'supervision_inspection/process_modification_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.flowmodify_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'modification_method': obj.modification_method,
                      'affiliation_model': obj.affiliation_model.name if obj.affiliation_model else "",
                      'reason': obj.reason,
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='process_modification_draft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='process_modification_detail.html?id={obj.id}'>查看</a> | <a href='process_modification_detail.html?revise=true&id={obj.id}'>修改</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.can_revise == '1' and obj.state != 'draft'
                      else f"<a href='process_modification_detail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='process_modification_detail.html?id={obj.id}'>查看</a>",
                      'state': obj.get_state_str()}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ProcessModificationIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        affiliation_obj = CustomerFormModule.objects.filter(~Q(id=100))
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "affiliation_obj": affiliation_obj, "uuid": uuid.uuid4()}
        return render(request, 'supervision_inspection/process_modification_index.html', context)

    def post(self, request):
        flow_id = request.POST.get("flow_id", '')
        affiliation_model = request.POST.get("affiliation_model", '')                               # 所属模块
        modify_flow = request.POST.get("modify_flow", '')                                   # 所属流程
        reason = request.POST.get("reason", '')                         # 修改原因
        note = request.POST.get("note", '')
        fj_number = request.POST.get("uuid", '')
        modification_method = request.POST.get("modification_method", '')

        if flow_id:
            obj = FlowModify.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.affiliation_model = CustomerFormModule.objects.get(id=int(affiliation_model))
            if modification_method == '1':
                obj.modify_flow = ProcessNodesMainTable.objects.get(id=int(modify_flow))
            obj.note = note
            obj.modification_method = modification_method
            obj.current_audit_users.clear()
            obj.flowmodifyrecord_set.filter(state="unaudit").delete()
            obj.save()
            message = "修改成功！"
        else:
            if modification_method == '1':
                obj = FlowModify.objects.create(apply_user=request.user, modification_method=modification_method, company=request.user.company, reason=reason, affiliation_model=CustomerFormModule.objects.get(id=int(affiliation_model)), modify_flow=ProcessNodesMainTable.objects.get(id=int(modify_flow)), note=note, fj_number=fj_number)
            else:
                obj = FlowModify.objects.create(apply_user=request.user, modification_method=modification_method, company=request.user.company, reason=reason, affiliation_model=CustomerFormModule.objects.get(id=int(affiliation_model)), note=note, fj_number=fj_number)
            message = "创建成功！"
        flag = True
        one_step = request.user.company.head_people  # 科主任
        if request.user != one_step:
            FlowModifyRecord.objects.create(parent_id=obj, node="one", audit_people=one_step, audit_note="", state="unaudit")
            obj.current_audit_users.add(one_step)
            obj.state = "one"
            flag = False

        two_step = request.user.company.leaders_id
        FlowModifyRecord.objects.create(parent_id=obj, node="two", audit_people=two_step, audit_note="", state="unaudit")
        if flag:
            obj.current_audit_users.add(two_step)
            obj.state = "two"

        three_step = Company.objects.get(id=31).head_people
        FlowModifyRecord.objects.create(parent_id=obj, node="three", audit_people=three_step, audit_note="", state="unaudit")

        obj.save()
        returnDict = {'code': 200, 'message': message}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ProcessModificationDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = FlowModify.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        affiliation_obj = CustomerFormModule.objects.filter(~Q(id=100))
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "revise": revise, "file_list": file_list, "affiliation_obj": affiliation_obj}
        return render(request, 'supervision_inspection/process_modification_draft.html', context)

    def post(self, request):
        flow_id = request.POST.get("flow_id", '')
        affiliation_model = request.POST.get("affiliation_model", '')                               # 所属模块
        modify_flow = request.POST.get("modify_flow", '')                                   # 所属流程
        reason = request.POST.get("reason", '')                         # 修改原因
        note = request.POST.get("note", '')
        fj_number = request.POST.get("uuid", '')
        modification_method = request.POST.get("modification_method", '')

        if flow_id:
            obj = FlowModify.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.affiliation_model = CustomerFormModule.objects.get(id=int(affiliation_model))
            if modification_method == '1':
                obj.modify_flow = ProcessNodesMainTable.objects.get(id=int(modify_flow))
            obj.note = note
        else:
            try:
                if modification_method == '1':
                    obj = FlowModify.objects.create(apply_user=request.user, modification_method=modification_method, company=request.user.company, reason=reason,
                                                    affiliation_model=CustomerFormModule.objects.get(id=int(affiliation_model)), modify_flow=ProcessNodesMainTable.objects.get(id=int(modify_flow)), note=note, fj_number=fj_number)
                else:
                    if affiliation_model != '0':
                        obj = FlowModify.objects.create(apply_user=request.user, modification_method=modification_method, company=request.user.company, reason=reason,
                                                    affiliation_model=CustomerFormModule.objects.get(id=int(affiliation_model)), note=note, fj_number=fj_number)
                    else:
                        obj = FlowModify.objects.create(apply_user=request.user, modification_method=modification_method,
                                                        company=request.user.company, reason=reason,  note=note, fj_number=fj_number)
            except:
                returnDict = {'code': 500, 'message': "保存失败，所属模块不能为空！"}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = "draft"
        obj.save()
        returnDict = {'code': 200, 'message': "保存成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ProcessModificationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = FlowModify.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.flowmodifyrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.flowmodifyrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "revise": revise, "leader_obj": User.objects.filter(group_id__in=[1, 2]),
                   "file_list": file_list, "audit_dic": audit_dic, "flow_dict": flow_dict, "affiliation_obj": CustomerFormModule.objects.filter(~Q(id=100)),
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'refuse'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'supervision_inspection/process_modification_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "流程节点修改")
        except:
            pass
        obj = FlowModify.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.flowmodifyrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.flowmodifyrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.flowmodifyrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.flowmodifyrecord_set.filter(node='three', state='unaudit')
                obj_state = 'three'
                for next_audit in next_audit_record:
                    obj.current_audit_users.add(next_audit.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.flowmodifyrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            obj.flowmodifyrecord_set.filter(~Q(audit_people=request.user), node='three', state='unaudit').delete()
            if state == 'audit':
                approve_leader = request.POST.get('approve_leader', "")
                five_step = Company.objects.get(id=31).head_people
                if approve_leader == "0":
                    obj_state = 'end'
                else:
                    obj_state = 'four'
                    four_step = User.objects.get(id=int(approve_leader))
                    FlowModifyRecord.objects.create(parent_id=obj, node="four", audit_people=four_step, audit_note="", state="unaudit")
                    obj.current_audit_users.add(four_step)
                    FlowModifyRecord.objects.create(parent_id=obj, node="five", audit_people=five_step, audit_note="", state="unaudit")
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.flowmodifyrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.flowmodifyrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.flowmodifyrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                obj_state = 'end'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ProcessModificationStop(View):
    def post(self, request):
        id = request.POST.get('id', None)
        types = request.POST.get('types', 'stop')  # stop 终止 delete 删除
        if types == 'stop':
            obj = FlowModify.objects.get(id=int(id))
            if obj.state == 'end':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的流程不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
                returnData = {'code': 200, 'message': '终止成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif types == 'search':
            model_id = request.POST.get("affiliation_model", "")
            print("affiliation_model: ", model_id)
            obj = CustomerFormModule.objects.get(id=int(model_id))
            flow_obj = obj.processnodesmaintable_set.all()
            flow_list = []
            for i in flow_obj:
                flow_list.append({"id": i.id, "name": i.process_name})
            returnData = {'code': 200, 'message': '查询成功！', "data": flow_list}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            obj = FlowModify.objects.get(id=int(id))
            obj.current_audit_users.clear()
            obj.flowmodifyrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

class DailyWorkList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        CompanyList = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in CompanyList:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)

        DailyList = []
        obj = DailyWorkSupervision.objects.filter(apply_user=request.user).order_by("-id")
        Serial = 1
        for i in obj[:20]:
            DailyList.append({"id": i.id, "title": i.title, "company": i.company.name, "start_time": i.start_time.strftime("%Y-%m-%d"), "end_time": i.end_time.strftime("%Y-%m-%d"),
                              "responsible_person": i.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count()//20 + 1 if obj.count()%20>0 else obj.count()//20
        page = 1
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page)+1, int(page)+2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page)+1, int(page)+2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page)-1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page)-2, int(page)-1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += ["...",  page_all_number - 5,  page_all_number - 4,  page_all_number - 3, page_all_number - 2, page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj+1)
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "company_list": company_list, "DailyList": DailyList, "pages": 1,
                   'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20, "page_list": page_list, "totals": obj.count(), "uuid": uuid.uuid4()}
        return render(request, 'supervision_inspection/daily_work_list.html', context)




class DailyWorkIndex(View):
    def post(self, request):
        title = request.POST.get("title", "")
        job_description = request.POST.get("job_description", "")
        company_id = request.POST.get("company", "")           # 责任科室
        start_time = request.POST.get("start_time", "")
        end_time = request.POST.get("end_time", "")
        responsible_person = request.POST.get("responsible_person", "")                 # 负责人
        collaboration = request.POST.get("collaboration", "")                       # 协作科室
        note = request.POST.get("note", "")
        fj_number = request.POST.get("fj_number", "")
        myFiles = request.FILES.get("file", "")
        file_path = os.path.join(os.getcwd(), f'static/supervision_inspection/attachment/{fj_number}')
        if not os.path.exists(file_path):
            os.mkdir(file_path)
        with open(os.path.join(file_path, myFiles.name), "wb") as F:
            for i in myFiles.chunks():
                F.write(i)

        CompanyId = re.findall('\((.*?)\)', company_id)
        person = re.findall('\((.*?)\)', responsible_person)
        CollId = re.findall('\((.*?)\)', collaboration)
        administrative_office = Company.objects.get(id=int(CompanyId[0]))
        ResponsiblePerson = User.objects.get(job_number=person[0])
        if CollId:
            technical_office = Company.objects.get(id=int(CollId[0]))
        else:
            technical_office = None
        DailyWorkSupervision.objects.create(apply_user=request.user, title=title, job_description=job_description, company=administrative_office, start_time=start_time,
                                            end_time=end_time, responsible_person=ResponsiblePerson, collaboration=technical_office, note=note, fj_number=fj_number, attachment_name=myFiles.name)
        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class DailyWorkDetail(View):
    def post(self, request):
        flow_id = request.POST.get("id", "")
        obj = DailyWorkSupervision.objects.get(id=int(flow_id))
        obj_detail = {
            "title": obj.title, "job_description": obj.job_description, "company": obj.company.name, "start_time": obj.start_time.strftime("%Y-%m-%d"), "end_time": obj.end_time.strftime("%Y-%m-%d"),
            "responsible_person": obj.responsible_person.real_name, "collaboration": obj.collaboration.name if obj.collaboration else "", "note": obj.note
        }
        RecordObj = obj.dailyworksupervisionrecord_set.all().order_by("-create_time")
        FeedbackList = [
            {"name": i.audit_people.real_name, "time": i.create_time.strftime("%Y-%m-%d %H:%M"), "audit_note": i.audit_note} for i in RecordObj
        ]
        FeedbackList.append({"name": obj.apply_user.real_name, "time": obj.create_time.strftime("%Y-%m-%d %H:%M"), "audit_note": "创建工作"})
        returnData = {'code': 200, 'message': '创建成功！', "obj_detail": obj_detail, "FeedbackList": FeedbackList, "feedback_flag": "true" if obj.state != "end" else "false"}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class MyAssistance(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        DailyList = []
        obj = DailyWorkSupervision.objects.filter(collaboration=request.user.company, collaboration__head_people=request.user).order_by("-id")
        Serial = 1
        for i in obj[:20]:
            DailyList.append({"id": i.id, "title": i.title, "company": i.company.name, "start_time": i.start_time.strftime("%Y-%m-%d"), "end_time": i.end_time.strftime("%Y-%m-%d"),
                              "responsible_person": i.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count()//20 + 1 if obj.count()%20>0 else obj.count()//20
        page = 1
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page)+1, int(page)+2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page)+1, int(page)+2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page)-1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page)-2, int(page)-1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += ["...",  page_all_number - 5,  page_all_number - 4,  page_all_number - 3, page_all_number - 2, page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj+1)
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "DailyList": DailyList, "pages": 1,
                   'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20, "page_list": page_list, "totals": obj.count()}
        return render(request, 'supervision_inspection/my_assistance.html', context)

class MyResponsible(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        DailyList = []
        obj = DailyWorkSupervision.objects.filter(responsible_person=request.user).order_by("-id")
        Serial = 1
        for i in obj[:20]:
            DailyList.append({"id": i.id, "title": i.title, "company": i.company.name, "start_time": i.start_time.strftime("%Y-%m-%d"), "end_time": i.end_time.strftime("%Y-%m-%d"),
                              "responsible_person": i.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count()//20 + 1 if obj.count()%20>0 else obj.count()//20
        page = 1
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page)+1, int(page)+2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page)+1, int(page)+2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page)-1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page)-2, int(page)-1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += ["...",  page_all_number - 5,  page_all_number - 4,  page_all_number - 3, page_all_number - 2, page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj+1)
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "DailyList": DailyList, "pages": 1,
                   'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20, "page_list": page_list, "totals": obj.count()}
        return render(request, 'supervision_inspection/my_responsible.html', context)

    def post(self, request):
        flow_id = request.POST.get("id", '')
        audit_note = request.POST.get("audit_note", '')
        flow_type = request.POST.get("flow_type", '')
        obj = DailyWorkSupervision.objects.get(id=int(flow_id))
        if flow_type != "end":
            RecordObj = DailyWorkSupervisionRecord.objects.create(parent_id=obj, audit_people=request.user, audit_note=audit_note)
            RecordObj.update_time = datetime.now()
            RecordObj.save()
        else:
            obj.state = "end"
            obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class WorkSupervisionList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        page = request.GET.get("page", 1)  # 页码
        CompanyList = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in CompanyList:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)

        DailyList = []
        obj = WorkSuperviseHandle.objects.filter(apply_user=request.user).order_by("-id")
        Serial = 1
        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20

        for i in obj[num1:num2]:
            DailyList.append({"id": i.id, "title": i.job_source, "company": i.company.name,
                              "start_time": i.start_time.strftime("%Y-%m-%d"), "state": i.state,
                              "end_time": i.end_time.strftime("%Y-%m-%d"), "appove": "true" if request.user in i.current_audit_users.all() else "false",
                              "responsible_person": i.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count() // 20 + 1 if obj.count() % 20 > 0 else obj.count() // 20
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...",
                                  page_all_number]
            else:
                page_list += ["...", page_all_number - 5, page_all_number - 4, page_all_number - 3, page_all_number - 2,
                              page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj + 1)

        sql = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state in ('five')"
        sql1 = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state='one'"
        sql2 = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND (B.state in ('two', 'three', 'four') or B.old_state in ('two', 'three', 'four'))"

        with connection.cursor() as cursor:
            cursor.execute(sql, {'audit_user': request.user.id})
            row = cursor.fetchone()

            cursor.execute(sql1, {'audit_user': request.user.id})
            row1 = cursor.fetchone()

            cursor.execute(sql2, {'audit_user': request.user.id})
            row2 = cursor.fetchone()

        add_flag = 'false'
        bgs_obj = Staffing.objects.get(station='工作督办添加人').post_personnel.all()
        if request.user in bgs_obj:
            add_flag = 'true'

        summit_flag = 'true' if request.user in Staffing.objects.get(station="医院办公室").post_personnel.all() else 'false'
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "company_list": company_list, "summit_flag": summit_flag, 'report_flag': 'true' if request.user.company.id == 80 else 'false',
                   "uuid": uuid.uuid4(), "DailyList": DailyList, "pages": int(page), 'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20, "page_list": page_list,
                   "totals": obj.count(), "my_add": "true" if row[0] else "flase", "oversight": "true" if row1[0] else "flase", "my_do": "true" if row2[0] else "flase", 'add_flag': add_flag}
        return render(request, 'supervision_inspection/work_supervision_list.html', context)

    def post(self, request):
        title = request.POST.get("title", "")                                   # 工作来源
        job_description = request.POST.get("job_description", "")           # 工作描述
        company_id = request.POST.get("company", "")           # 责任科室
        start_time = request.POST.get("start_time", "")
        end_time = request.POST.get("end_time", "")
        responsible_person = request.POST.get("responsible_person", "")                 # 负责人
        complete_requirements = request.POST.get("complete_requirements", "")               # 完成要求
        note = request.POST.get("note", "")
        fj_number = request.POST.get("fj_number", "")
        myFiles = request.FILES.get("file", "")
        file_path = os.path.join(os.getcwd(), f'static/supervision_inspection/attachment_first_level/{fj_number}')
        if not os.path.exists(file_path):
            os.mkdir(file_path)
        with open(os.path.join(file_path, myFiles.name), "wb") as F:
            for i in myFiles.chunks():
                F.write(i)

        CompanyId = re.findall('\((.*?)\)', company_id)
        person = re.findall('\((.*?)\)', responsible_person)
        administrative_office = Company.objects.get(id=int(CompanyId[0]))
        ResponsiblePerson = User.objects.get(job_number=person[0])
        zgb_leader = Company.objects.get(id=4).head_people
        obj = WorkSuperviseHandle.objects.create(apply_user=request.user, job_source=title, job_description=job_description, company=administrative_office, start_time=start_time, state="one",
                                            end_time=end_time, responsible_person=ResponsiblePerson, complete_requirements=complete_requirements, note=note, fj_number=fj_number, attachment_name=myFiles.name)
        obj.current_audit_users.add(ResponsiblePerson)
        WorkSuperviseHandleRecord.objects.create(parent_id=obj, state='unaudit', node='one', audit_people=ResponsiblePerson, audit_note='')
        WorkSuperviseHandleRecord.objects.create(parent_id=obj, state='unaudit', node='two', audit_people=administrative_office.leaders_id, audit_note='')
        WorkSuperviseHandleRecord.objects.create(parent_id=obj, state='unaudit', node='three', audit_people=zgb_leader, audit_note='')
        WorkSuperviseHandleRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=request.user, audit_note='')
        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class WorkSupervisionDetail(View):
    def post(self, request):
        flow_id = request.POST.get("id", "")
        DeadId = request.POST.get("type", "")

        obj = WorkSuperviseHandle.objects.get(id=int(flow_id))

        if DeadId:
            DeadObj = DeadlineNotification.objects.get(id=int(DeadId))
            if DeadObj.view_or_not == '0':
                DeadObj.current_audit_users.clear()
                DeadObj.state = "one"
                DeadObj.view_or_not = "1"
                DeadObj.current_audit_users.add(obj.responsible_person)
                DeadObj.save()
                obj.state = "one"
                obj.save()

        obj_detail = {
            "title": obj.job_source, "job_description": obj.job_description, "company": obj.company.name, "start_time": obj.start_time.strftime("%Y-%m-%d"), "end_time": obj.end_time.strftime("%Y-%m-%d"),
            "responsible_person": obj.responsible_person.real_name, "complete_requirements": obj.complete_requirements, "note": obj.note
        }
        RecordObj = obj.worksupervisehandlerecord_set.filter(~Q(state='unaudit')).order_by("-update_time")
        FeedbackList, flow_dict, sear = [], {}, 1
        for i in RecordObj:
            FeedbackList.append({"name": i.audit_people.real_name, "time": i.update_time.strftime("%Y-%m-%d %H:%M"), "audit_note": '转审' if i.state== 'referee' and not i.audit_note else i.audit_note if i.audit_note else '同意', "file_path": i.file_path.replace(os.getcwd(), ""), 'state': '转审' if i.state == 'referee' else "拒绝" if i.state == 'draft' else "同意"})
            sear += 1
        file_list = {"file_name": obj.attachment_name, "file_path": f'/static/supervision_inspection/attachment_first_level/{obj.fj_number}/{obj.attachment_name}'}

        one_step = obj.worksupervisehandlerecord_set.filter(node='one')
        one_audit_people = []
        one_status = 'audit'
        for one in one_step:
            one_audit_people.append(one.audit_people.real_name)
            if one.state == "unaudit":
                one_status = 'unaudit'
        flow_dict['one'] = {"name": ', '.join(list(set(one_audit_people))), "status": one_status}

        if obj.worksupervisehandlerecord_set.filter(node='two'):
            two_step = obj.worksupervisehandlerecord_set.filter(node='two')
            two_audit_people = []
            two_status = 'audit'
            for two in two_step:
                two_audit_people.append(two.audit_people.real_name)
                if two.state == "unaudit":
                    two_status = 'unaudit'
            flow_dict['two'] = {"name": ', '.join(list(set(two_audit_people))), "status": two_status}

        three_step = obj.worksupervisehandlerecord_set.filter(node='three')
        three_audit_people = []
        three_status = 'audit'
        for three in three_step:
            three_audit_people.append(three.audit_people.real_name)
            if three.state == "unaudit":
                three_status = 'unaudit'
        flow_dict['three'] = {"name": ', '.join(list(set(three_audit_people))), "status": three_status}

        if obj.worksupervisehandlerecord_set.filter(node='four'):
            four_step = obj.worksupervisehandlerecord_set.filter(node='four')
            four_audit_people = []
            four_status = 'audit'
            for four in four_step:
                four_audit_people.append(four.audit_people.real_name)
                if four.state == "unaudit":
                    four_status = 'unaudit'
            flow_dict['four'] = {"name": ', '.join(list(set(four_audit_people))), "status": four_status}

        five_step = obj.worksupervisehandlerecord_set.filter(node='five')
        five_audit_people = []
        five_status = 'audit'
        for five in five_step:
            five_audit_people.append(five.audit_people.real_name)
            if five.state == "unaudit":
                five_status = 'unaudit'
        flow_dict['five'] = {"name": ', '.join(list(set(five_audit_people))), "status": five_status}

        FeedbackList.append({"name": obj.apply_user.real_name, "time": obj.create_time.strftime("%Y-%m-%d %H:%M"), "audit_note": "创建工作", 'file_path': '', 'state': '创建'})
        returnData = {'code': 200, 'message': '创建成功！', "obj_detail": obj_detail, "FeedbackList": FeedbackList, 'flow_dict': flow_dict, "fj_number": obj.fj_number,
                      "feedback_flag": "true" if obj.state != "end" else "false", "files": file_list, "flow_id": obj.id, "state": obj.state}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class WorkOperations(View):
    def post(self, request):
        flow_id = request.POST.get("id", "")
        type_s = request.POST.get("type", "")
        audit_note = request.POST.get("audit_note", "")
        obj = WorkSuperviseHandle.objects.get(id=int(flow_id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.remove(request.user)

        feedback_file = request.POST.get("file", "")
        file_path = os.path.join(os.getcwd(), f'static/supervision_inspection/feedback_file/{obj.fj_number}')
        if not os.path.exists(file_path):
            os.makedirs(file_path)

        if type_s == "end":
            obj.current_audit_users.clear()
            audit_record = obj.worksupervisehandlerecord_set.filter(state='unaudit', audit_people=request.user).first()
            obj.state = "end"
            obj.save()
            audit_record.update_time = datetime.now()
            audit_record.state = 'audit'
            audit_record.audit_note = audit_note
            audit_record.file_path = os.path.join(file_path, feedback_file.name) if feedback_file else ""
            audit_record.save()

        elif type_s == "back":
            if obj.state == "one":
                returnData = {'code': 400, 'message': '当前节点无法退回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.responsible_person)
                obj.state = "one"
                obj.save()

                audit_record = obj.worksupervisehandlerecord_set.filter(state='unaudit', audit_people=request.user).first()
                audit_record.update_time = datetime.now()
                audit_record.state = 'draft'
                audit_record.audit_note = audit_note
                audit_record.file_path = os.path.join(file_path, feedback_file.name) if feedback_file else ""
                audit_record.save()

                zgb_leader = Company.objects.get(id=4).head_people
                obj.worksupervisehandlerecord_set.filter(state='unaudit').delete()
                WorkSuperviseHandleRecord.objects.create(parent_id=obj, state='unaudit', node='one', audit_people=obj.responsible_person, audit_note='')
                WorkSuperviseHandleRecord.objects.create(parent_id=obj, state='unaudit', node='two', audit_people=obj.company.leaders_id, audit_note='')
                WorkSuperviseHandleRecord.objects.create(parent_id=obj, state='unaudit', node='three', audit_people=zgb_leader, audit_note='')
                WorkSuperviseHandleRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=obj.apply_user, audit_note='')

        else:
            all_file_path_list = []
            if feedback_file:
                for f_n in json.loads(feedback_file):
                    all_file_path_list.append(os.path.join(file_path, f_n))

            if obj.state == "one":
                audit_record = obj.worksupervisehandlerecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
                audit_record.state = 'audit'
                if not obj.current_audit_users.all().count():
                    if obj.worksupervisehandlerecord_set.filter(node='two').count():
                        next_record = obj.worksupervisehandlerecord_set.filter(node='two', state='unaudit')
                        obj.state = "two"
                    else:
                        next_record = obj.worksupervisehandlerecord_set.filter(node='three', state='unaudit')
                        obj.state = "three"
                    for two_record in next_record:
                        obj.current_audit_users.add(two_record.audit_people)
                else:
                    obj.state = "one"
                obj.save()

            elif obj.state == "two":
                audit_record = obj.worksupervisehandlerecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
                audit_record.state = 'audit'
                if not obj.current_audit_users.all().count():
                    next_record = obj.worksupervisehandlerecord_set.filter(node='three', state='unaudit')
                    for three_record in next_record:
                        obj.current_audit_users.add(three_record.audit_people)
                    obj.state = "three"
                else:
                    obj.state = "two"
                obj.save()

            elif obj.state == "three":
                audit_record = obj.worksupervisehandlerecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
                referee = request.POST.get("referee", "")
                referee_people_list = re.findall('\((.*?)\)', referee)
                if referee_people_list:
                    audit_record.state = 'referee'
                    for referee_people in referee_people_list:
                        four_appove_people = User.objects.get(job_number=referee_people)
                        WorkSuperviseHandleRecord.objects.create(parent_id=obj, state='unaudit', node='four', audit_people=four_appove_people, audit_note='')
                        obj.current_audit_users.add(four_appove_people)
                    obj.state = "four"
                else:
                    next_record = obj.worksupervisehandlerecord_set.filter(node='five', state='unaudit')
                    audit_record.state = 'audit'
                    for five_record in next_record:
                        obj.current_audit_users.add(five_record.audit_people)
                    obj.state = "five"
                obj.save()

            elif obj.state == "four":
                audit_record = obj.worksupervisehandlerecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
                audit_record.state = 'audit'
                if not obj.current_audit_users.all().count():
                    next_record = obj.worksupervisehandlerecord_set.filter(node='five', state='unaudit')
                    for five_record in next_record:
                        obj.current_audit_users.add(five_record.audit_people)
                    obj.state = "five"
                    obj.save()

            else:
                audit_record = obj.worksupervisehandlerecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
                audit_record.state = 'audit'
                obj.current_audit_users.clear()
                obj.state = "end"
                obj.save()

                if obj.transfer_supervision_office == '1':
                    DeadlineObj = DeadlineNotification.objects.filter(work_id=obj).first()
                    DeadlineObj.state = 'end'
                    DeadlineObj.save()
            audit_record.update_time = datetime.now()
            audit_record.audit_note = audit_note
            audit_record.file_path = ",".join(all_file_path_list) if all_file_path_list else ""
            audit_record.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class MyConscientious(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        page = request.GET.get("page", 1)  # 页码
        CompanyList = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in CompanyList:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)

        DailyList = []
        obj = WorkSuperviseHandle.objects.filter(responsible_person=request.user).order_by("-id")
        Serial = 1
        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20

        for i in obj[num1:num2]:
            DailyList.append({"id": i.id, "title": i.job_source, "company": i.company.name,
                              "start_time": i.start_time.strftime("%Y-%m-%d"), "state": i.state, "transfer_supervision_office": i.transfer_supervision_office,
                              "end_time": i.end_time.strftime("%Y-%m-%d"), "appove": "true" if request.user in i.current_audit_users.all() else "false",
                              "responsible_person": i.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count() // 20 + 1 if obj.count() % 20 > 0 else obj.count() // 20
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...",
                                  page_all_number]
            else:
                page_list += ["...", page_all_number - 5, page_all_number - 4, page_all_number - 3, page_all_number - 2,
                              page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj + 1)

        sql = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state in ('five')"
        sql1 = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state='one'"
        sql2 = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND (B.state in ('two', 'three', 'four') or B.old_state in ('two', 'three', 'four'))"

        with connection.cursor() as cursor:
            cursor.execute(sql, {'audit_user': request.user.id})
            row = cursor.fetchone()

            cursor.execute(sql1, {'audit_user': request.user.id})
            row1 = cursor.fetchone()

            cursor.execute(sql2, {'audit_user': request.user.id})
            row2 = cursor.fetchone()

        summit_flag = 'true' if request.user in Staffing.objects.get(station="医院办公室").post_personnel.all() else 'false'
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "company_list": company_list, "summit_flag": summit_flag,
                   "DailyList": DailyList, "pages": int(page), 'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20, "page_list": page_list, 'report_flag': 'true' if request.user.company.id == 80 else 'false',
                   "totals": obj.count(), "my_add": "true" if row[0] else "flase", "oversight": "true" if row1[0] else "flase", "my_do": "true" if row2[0] else "flase"}
        return render(request, 'supervision_inspection/my_conscientious.html', context)

class MyNeedDo(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        page = request.GET.get("page", 1)  # 页码
        CompanyList = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in CompanyList:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)

        DailyList = []
        obj = WorkSuperviseHandle.objects.filter(Q(state__in=['two', 'three', 'four']) | Q(old_state__in=['two', 'three', 'four']) , current_audit_users=request.user).order_by("-id")
        Serial = 1
        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20

        for i in obj[num1:num2]:
            DailyList.append({"id": i.id, "title": i.job_source, "company": i.company.name,
                              "start_time": i.start_time.strftime("%Y-%m-%d"), "state": i.state,
                              "end_time": i.end_time.strftime("%Y-%m-%d"), "appove": "true" if request.user in i.current_audit_users.all() else "false",
                              "responsible_person": i.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count() // 20 + 1 if obj.count() % 20 > 0 else obj.count() // 20
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...",
                                  page_all_number]
            else:
                page_list += ["...", page_all_number - 5, page_all_number - 4, page_all_number - 3, page_all_number - 2,
                              page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj + 1)

        sql = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state in ('five')"
        sql1 = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state='one'"
        sql2 = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND (B.state in ('two', 'three', 'four') or B.old_state in ('two', 'three', 'four'))"

        with connection.cursor() as cursor:
            cursor.execute(sql, {'audit_user': request.user.id})
            row = cursor.fetchone()

            cursor.execute(sql1, {'audit_user': request.user.id})
            row1 = cursor.fetchone()

            cursor.execute(sql2, {'audit_user': request.user.id})
            row2 = cursor.fetchone()

        summit_flag = 'true' if request.user in Staffing.objects.get(station="医院办公室").post_personnel.all() else 'false'
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "company_list": company_list, "summit_flag": summit_flag,
                   "DailyList": DailyList, "pages": int(page), 'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20, "page_list": page_list, 'report_flag': 'true' if request.user.company.id == 80 else 'false',
                   "totals": obj.count(), "my_add": "true" if row[0] else "flase", "oversight": "true" if row1[0] else "flase", "my_do": "true" if row2[0] else "flase"}
        return render(request, 'supervision_inspection/my_need_do.html', context)

class MyAlreadyDone(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        page = request.GET.get("page", 1)  # 页码
        CompanyList = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in CompanyList:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)

        DailyList = []
        obj = WorkSuperviseHandle.objects.filter(audit_users_already=request.user).order_by("-id")
        Serial = 1
        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20

        for i in obj[num1:num2]:
            DailyList.append({"id": i.id, "title": i.job_source, "company": i.company.name,
                              "start_time": i.start_time.strftime("%Y-%m-%d"), "state": i.state,
                              "end_time": i.end_time.strftime("%Y-%m-%d"), "appove": "true" if request.user in i.current_audit_users.all() else "false",
                              "responsible_person": i.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count() // 20 + 1 if obj.count() % 20 > 0 else obj.count() // 20
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...",
                                  page_all_number]
            else:
                page_list += ["...", page_all_number - 5, page_all_number - 4, page_all_number - 3, page_all_number - 2,
                              page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj + 1)

        sql = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state in ('three', 'five')"
        sql1 = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state='one'"
        sql2 = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND (B.state in ('two', 'three', 'four') or B.old_state in ('two', 'three', 'four'))"

        with connection.cursor() as cursor:
            cursor.execute(sql, {'audit_user': request.user.id})
            row = cursor.fetchone()

            cursor.execute(sql1, {'audit_user': request.user.id})
            row1 = cursor.fetchone()

            cursor.execute(sql2, {'audit_user': request.user.id})
            row2 = cursor.fetchone()

        summit_flag = 'true' if request.user in Staffing.objects.get(station="医院办公室").post_personnel.all() else 'false'
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "company_list": company_list, "summit_flag": summit_flag,
                   "DailyList": DailyList, "pages": int(page), 'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20, "page_list": page_list, 'report_flag': 'true' if request.user.company.id == 80 else 'false',
                   "totals": obj.count(), "my_add": "true" if row[0] else "flase", "oversight": "true" if row1[0] else "flase", "my_do": "true" if row2[0] else "flase"}
        return render(request, 'supervision_inspection/my_already_done.html', context)

class WorkReport(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        page = request.GET.get("page", 1)              # 页码
        CompanyList = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in CompanyList:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)

        DailyList = []
        obj = WorkSuperviseHandle.objects.all().order_by("-id")
        Serial = 1

        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20

        for i in obj[num1:num2]:
            DailyList.append({"id": i.id, "title": i.job_source, "company": i.company.name, "apply_user": i.apply_user.real_name,
                              "start_time": i.start_time.strftime("%Y-%m-%d"), "state": i.state,
                              "end_time": i.end_time.strftime("%Y-%m-%d"), "appove": "true" if request.user in i.current_audit_users.all() else "false",
                              "responsible_person": i.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count() // 20 + 1 if obj.count() % 20 > 0 else obj.count() // 20
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...",
                                  page_all_number]
            else:
                page_list += ["...", page_all_number - 5, page_all_number - 4, page_all_number - 3, page_all_number - 2,
                              page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj + 1)

        sql = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state in ('three', 'five')"
        sql1 = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state='one'"
        sql2 = "SELECT COUNT(*) AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state in ('two', 'four')"

        with connection.cursor() as cursor:
            cursor.execute(sql, {'audit_user': request.user.id})
            row = cursor.fetchone()

            cursor.execute(sql1, {'audit_user': request.user.id})
            row1 = cursor.fetchone()

            cursor.execute(sql2, {'audit_user': request.user.id})
            row2 = cursor.fetchone()
        print("======================", page, page_list)
        summit_flag = 'true' if request.user in Staffing.objects.get(station="医院办公室").post_personnel.all() else 'false'
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "company_list": company_list, "summit_flag": summit_flag,
                   "DailyList": DailyList, "pages": int(page), 'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20, "page_list": page_list, 'report_flag': 'true' if request.user.company.id == 80 else 'false',
                   "totals": obj.count(), "my_add": "true" if row[0] else "flase", "oversight": "true" if row1[0] else "flase", "my_do": "true" if row2[0] else "flase"}
        return render(request, 'supervision_inspection/work_report.html', context)

class OverdueNotice(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        page = request.GET.get("page", 1)  # 页码

        DailyList = []
        obj = OverdueFlow.objects.filter(process_owner=request.user).order_by("-id")
        Serial = 1
        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20

        for i in obj[num1:num2]:
            DailyList.append({"id": i.parent_id.id, "title": i.parent_id.job_source, "company": i.parent_id.company.name,
                              "start_time": i.parent_id.start_time.strftime("%Y-%m-%d"), "flow_id": i.id,
                              "end_time": i.parent_id.end_time.strftime("%Y-%m-%d"), "deadline": i.deadline,
                              "responsible_person": i.parent_id.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count() // 20 + 1 if obj.count() % 20 > 0 else obj.count() // 20
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...",
                                  page_all_number]
            else:
                page_list += ["...", page_all_number - 5, page_all_number - 4, page_all_number - 3, page_all_number - 2,
                              page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj + 1)

        jcs_head_obj = Company.objects.get(id=18).head_people
        OverdueFlag = OverdueFlow.objects.filter(process_owner=request.user, deadline="0").count()
        deadline_flag = DeadlineNotification.objects.filter(current_audit_users=request.user, state='one').count()
        my_launch_flag = 1 if DeadlineNotification.objects.filter(end_deadline_time__lt=datetime.now(), work_id__state__in=['one', 'two'], initiate_or_not='0').count() and request.user == jcs_head_obj else 0
        overdue_process_flag = DeadlineNotification.objects.filter(state="zero", current_audit_users=request.user, view_or_not='0').count()
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "overdue_process_flag": overdue_process_flag,
                   "DailyList": DailyList, "pages": int(page), 'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20,
                   "page_list": page_list, "totals": obj.count(), "OverdueFlag": OverdueFlag, "deadline_flag": deadline_flag, "my_launch_flag": my_launch_flag}
        return render(request, 'supervision_inspection/overdue_notice.html', context)

class InitiationDeadline(View):
    def post(self, request):
        flow_id = request.POST.get("id", "")
        current_id = request.POST.get("flow_id", "")
        grace_days = request.POST.get("grace_days", "")
        end_time = datetime.today().date() + timedelta(days=int(grace_days)-1)

        work_obj = WorkSuperviseHandle.objects.get(id=int(flow_id))
        overdu_obj = OverdueFlow.objects.get(id=int(current_id))
        obj = DeadlineNotification.objects.create(work_id=work_obj, end_deadline_time=end_time, overdue_id=overdu_obj, apply_user=request.user,
                                                  responsible_person=work_obj.responsible_person)

        flow_obj = WorkSuperviseHandle.objects.get(id=int(flow_id))
        WorkSuperviseHandleRecord.objects.create(parent_id=flow_obj, state="audit", node="ten", audit_people=request.user,
                                                 audit_note=f"延期至{str(obj.end_deadline_time).split(' ')[0]}")

        obj.current_audit_users.add(work_obj.company.leaders_id)
        obj.state = "zero"
        obj.leaders_obj = work_obj.company.leaders_id
        obj.save()
        overdu_obj.current_audit_users.clear()
        overdu_obj.deadline = "1"
        overdu_obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class DeadlineProcess(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        page = request.GET.get("page", 1)  # 页码

        DailyList = []
        obj = DeadlineNotification.objects.filter(responsible_person=request.user).order_by("-id")
        Serial = 1
        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20

        for i in obj[num1:num2]:
            DailyList.append({"id": i.work_id.id, "title": i.work_id.job_source, "company": i.work_id.company.name,
                              "start_time": i.work_id.start_time.strftime("%Y-%m-%d"), "flow_id": i.id, "state": i.state,
                              "end_time": i.work_id.end_time.strftime("%Y-%m-%d"), "appove": "true" if request.user in i.current_audit_users.all() else "false",
                              "responsible_person": i.work_id.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count() // 20 + 1 if obj.count() % 20 > 0 else obj.count() // 20
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...",
                                  page_all_number]
            else:
                page_list += ["...", page_all_number - 5, page_all_number - 4, page_all_number - 3, page_all_number - 2,
                              page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj + 1)

        jcs_head_obj = Company.objects.get(id=18).head_people
        OverdueFlag = OverdueFlow.objects.filter(process_owner=request.user, deadline="0").count()
        deadline_flag = DeadlineNotification.objects.filter(current_audit_users=request.user, state='one').count()
        my_launch_flag = 1 if DeadlineNotification.objects.filter(end_deadline_time__lt=datetime.now(), work_id__state__in=['one', 'two'], initiate_or_not='0').count() and request.user == jcs_head_obj else 0
        overdue_process_flag = DeadlineNotification.objects.filter(state="zero", current_audit_users=request.user, view_or_not='0').count()
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "overdue_process_flag": overdue_process_flag,
                   "DailyList": DailyList, "pages": int(page), 'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20,
                   "page_list": page_list, "totals": obj.count(), "OverdueFlag": OverdueFlag, "deadline_flag": deadline_flag, "my_launch_flag": my_launch_flag}
        return render(request, 'supervision_inspection/deadline_process.html', context)

class DeadlineFeedback(View):
    def post(self, request):
        work_id = request.POST.get("work_id", "")                                   # 工作流程ID
        deadline_id = request.POST.get("deadline_id", "")                           # 限期流程ID
        audit_note = request.POST.get("audit_note", "")                             # 流程反馈意见
        type_s = request.POST.get("type", "")

        work_obj = WorkSuperviseHandle.objects.get(id=int(work_id))
        deadline_obj = DeadlineNotification.objects.get(id=int(deadline_id))
        deadline_obj.current_audit_users.clear()
        deadline_obj.audit_users_already.add(request.user)

        feedback_file = request.POST.get("file", "")
        file_path = os.path.join(os.getcwd(), f'static/supervision_inspection/feedback_file/{work_obj.fj_number}')
        if not os.path.exists(file_path):
            os.makedirs(file_path)

        all_file_path_list = []
        for f_n in json.loads(feedback_file):
            all_file_path_list.append(os.path.join(file_path, f_n))
        if type_s == "end":
            work_obj.current_audit_users.clear()
            audit_record = work_obj.worksupervisehandlerecord_set.filter(state='unaudit', audit_people=request.user).first()
            work_obj.state = "end"
            work_obj.save()
            audit_record.update_time = datetime.now()
            audit_record.state = 'audit'
            audit_record.audit_note = audit_note
            audit_record.file_path = os.path.join(file_path, feedback_file.name) if feedback_file else ""
            audit_record.save()

        elif type_s == "back":
            if work_obj.state == "one":
                returnData = {'code': 400, 'message': '当前节点无法退回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                work_obj.current_audit_users.clear()
                work_obj.current_audit_users.add(work_obj.responsible_person)
                work_obj.state = "one"
                work_obj.save()

                audit_record = work_obj.worksupervisehandlerecord_set.filter(state='unaudit', audit_people=request.user).first()
                audit_record.update_time = datetime.now()
                audit_record.state = 'draft'
                audit_record.audit_note = audit_note
                audit_record.file_path = os.path.join(file_path, feedback_file.name) if feedback_file else ""
                audit_record.save()

                zgb_leader = Company.objects.get(id=4).head_people
                work_obj.worksupervisehandlerecord_set.filter(state='unaudit').delete()
                WorkSuperviseHandleRecord.objects.create(parent_id=work_obj, state='unaudit', node='one', audit_people=work_obj.responsible_person, audit_note='')
                WorkSuperviseHandleRecord.objects.create(parent_id=work_obj, state='unaudit', node='two', audit_people=work_obj.company.leaders_id, audit_note='')
                WorkSuperviseHandleRecord.objects.create(parent_id=work_obj, state='unaudit', node='three', audit_people=zgb_leader, audit_note='')
                WorkSuperviseHandleRecord.objects.create(parent_id=work_obj, state='unaudit', node='five', audit_people=work_obj.apply_user, audit_note='')

        else:
            if work_obj.state == "one":
                audit_record = work_obj.worksupervisehandlerecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
                audit_record.state = 'audit'
                if not work_obj.current_audit_users.all().count():
                    if work_obj.worksupervisehandlerecord_set.filter(node='two').count():
                        next_record = work_obj.worksupervisehandlerecord_set.filter(node='two', state='unaudit')
                        work_obj.state = "two"
                    else:
                        next_record = work_obj.worksupervisehandlerecord_set.filter(node='three', state='unaudit')
                        work_obj.state = "three"
                    for two_record in next_record:
                        work_obj.current_audit_users.add(two_record.audit_people)
                else:
                    work_obj.state = "one"
                work_obj.save()

            elif work_obj.state == "two":
                audit_record = work_obj.worksupervisehandlerecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
                audit_record.state = 'audit'
                if not work_obj.current_audit_users.all().count():
                    next_record = work_obj.worksupervisehandlerecord_set.filter(node='three', state='unaudit')
                    for three_record in next_record:
                        work_obj.current_audit_users.add(three_record.audit_people)
                    work_obj.state = "three"
                else:
                    work_obj.state = "two"
                work_obj.save()

            elif work_obj.state == "three":
                audit_record = work_obj.worksupervisehandlerecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
                referee = request.POST.get("referee", "")
                referee_people_list = re.findall('\((.*?)\)', referee)
                if referee_people_list:
                    audit_record.state = 'referee'
                    for referee_people in referee_people_list:
                        four_appove_people = User.objects.get(job_number=referee_people)
                        WorkSuperviseHandleRecord.objects.create(parent_id=work_obj, state='unaudit', node='four', audit_people=four_appove_people, audit_note='')
                        work_obj.current_audit_users.add(four_appove_people)
                    work_obj.state = "four"
                else:
                    next_record = work_obj.worksupervisehandlerecord_set.filter(node='five', state='unaudit')
                    audit_record.state = 'audit'
                    for five_record in next_record:
                        work_obj.current_audit_users.add(five_record.audit_people)
                    work_obj.state = "five"
                work_obj.save()

            elif work_obj.state == "four":
                audit_record = work_obj.worksupervisehandlerecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
                audit_record.state = 'audit'
                if not work_obj.current_audit_users.all().count():
                    next_record = work_obj.worksupervisehandlerecord_set.filter(node='five', state='unaudit')
                    for five_record in next_record:
                        work_obj.current_audit_users.add(five_record.audit_people)
                    work_obj.state = "five"
                    work_obj.save()
            else:
                audit_record = work_obj.worksupervisehandlerecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
                audit_record.state = 'audit'
                work_obj.current_audit_users.clear()
                work_obj.state = "end"
                work_obj.save()
            audit_record.update_time = datetime.now()
            audit_record.audit_note = audit_note
            audit_record.file_path = ",".join(all_file_path_list) if all_file_path_list else ""
            audit_record.save()

        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class FinishJob(View):
    def post(self, request):
        flow_id = request.POST.get("flow_id", "")                                   # 工作流程ID
        current_id = request.POST.get("current_id", "")

        obj = DeadlineNotification.objects.get(id=int(current_id))
        obj.current_audit_users.clear()
        flow_obj = WorkSuperviseHandle.objects.get(id=int(flow_id))
        WorkSuperviseHandleRecord.objects.create(parent_id=flow_obj, state="audit", node="three", audit_people=request.user, audit_note="完结工作")
        obj.state = "end"
        obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ExtendedThePeriod(View):
    def post(self, request):
        flow_id = request.POST.get("flow_id", "")                                   # 工作流程ID
        current_id = request.POST.get("current_id", "")
        destiny = request.POST.get("destiny", "")

        obj = DeadlineNotification.objects.get(id=int(current_id))

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        obj.state = "one"
        obj.end_deadline_time = obj.end_deadline_time + timedelta(days=int(destiny)-1)
        obj.current_audit_users.add(obj.responsible_person)
        flow_obj = WorkSuperviseHandle.objects.get(id=int(flow_id))
        WorkSuperviseHandleRecord.objects.create(parent_id=flow_obj, state="audit", node="ten", audit_people=request.user,
                                                 audit_note=f"延期至{str(obj.end_deadline_time).split(' ')[0]}")
        obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class MyInstigation(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        page = request.GET.get("page", 1)  # 页码

        DailyList = []
        obj = DeadlineNotification.objects.filter(apply_user=request.user).order_by("-id")
        Serial = 1
        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20

        for i in obj[num1:num2]:
            DailyList.append({"id": i.work_id.id, "title": i.work_id.job_source, "company": i.work_id.company.name, "overdue": 'true' if datetime.now() > i.end_deadline_time and i.initiate_or_not == '0' and i.work_id.state in ["one", "two"] else "false",
                              "start_time": i.work_id.start_time.strftime("%Y-%m-%d"), "flow_id": i.id, "state": i.state, "end_deadline_time": i.end_deadline_time.strftime("%Y-%m-%d"),
                              "end_time": i.work_id.end_time.strftime("%Y-%m-%d"), "appove": "true" if request.user in i.current_audit_users.all() else "false", 'initiate_or_not': i.initiate_or_not,
                              "responsible_person": i.work_id.responsible_person.real_name, "Serial": Serial})
            Serial += 1
        page_all_number = obj.count() // 20 + 1 if obj.count() % 20 > 0 else obj.count() // 20
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...",
                                  page_all_number]
            else:
                page_list += ["...", page_all_number - 5, page_all_number - 4, page_all_number - 3, page_all_number - 2,
                              page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj + 1)

        jcs_head_obj = Company.objects.get(id=18).head_people
        OverdueFlag = OverdueFlow.objects.filter(process_owner=request.user, deadline="0").count()
        deadline_flag = DeadlineNotification.objects.filter(current_audit_users=request.user, state='one').count()
        my_launch_flag = 1 if DeadlineNotification.objects.filter(end_deadline_time__lt=datetime.now(), work_id__state__in=['one', 'two'], initiate_or_not='0').count() and request.user == jcs_head_obj else 0
        overdue_process_flag = DeadlineNotification.objects.filter(state="zero", current_audit_users=request.user, view_or_not='0').count()
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "overdue_process_flag": overdue_process_flag,
                   "DailyList": DailyList, "pages": int(page), 'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20,
                   "page_list": page_list, "totals": obj.count(), "OverdueFlag": OverdueFlag, "deadline_flag": deadline_flag, "my_launch_flag": my_launch_flag}
        return render(request, 'supervision_inspection/my_instigation.html', context)


class OverdueProcess(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        page = request.GET.get("page", 1)  # 页码

        DailyList = []
        obj = DeadlineNotification.objects.filter(leaders_obj=request.user).order_by("-id")
        Serial = 1
        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20

        for i in obj[num1:num2]:
            DailyList.append({"id": i.work_id.id, "title": i.work_id.job_source, "company": i.work_id.company.name, "overdue": 'true' if datetime.now() > i.end_deadline_time and i.initiate_or_not == '0' and i.work_id.state in ["one", "two"] else "false",
                              "start_time": i.work_id.start_time.strftime("%Y-%m-%d"), "flow_id": i.id, "state": i.state, "end_deadline_time": i.end_deadline_time.strftime("%Y-%m-%d"),
                              "end_time": i.work_id.end_time.strftime("%Y-%m-%d"), "appove": "true" if request.user in i.current_audit_users.all() else "false", 'initiate_or_not': i.initiate_or_not,
                              "responsible_person": i.work_id.responsible_person.real_name, "Serial": Serial, "view_or_not": i.view_or_not})
            Serial += 1
        page_all_number = obj.count() // 20 + 1 if obj.count() % 20 > 0 else obj.count() // 20
        if page_all_number > 5 and page_all_number < 8:
            page_list = [1]
            if int(page) == 1:
                page_list = [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 2:
                page_list += [int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            elif int(page) == 3:
                page_list += [int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...", page_all_number]
            else:
                page_list += [int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, page_all_number]
        elif page_all_number >= 8:
            page_list = [1]
            if page_all_number - int(page) > 3:
                if int(page) <= 5:
                    page_list += [2, 3, 4, 5, 6, "...", page_all_number]
                else:
                    page_list += ["...", int(page) - 2, int(page) - 1, int(page), int(page) + 1, int(page) + 2, "...",
                                  page_all_number]
            else:
                page_list += ["...", page_all_number - 5, page_all_number - 4, page_all_number - 3, page_all_number - 2,
                              page_all_number - 1, page_all_number]
        else:
            page_list = []
            for jj in range(page_all_number):
                page_list.append(jj + 1)

        jcs_head_obj = Company.objects.get(id=18).head_people
        OverdueFlag = OverdueFlow.objects.filter(process_owner=request.user, deadline="0").count()
        deadline_flag = DeadlineNotification.objects.filter(current_audit_users=request.user, state='one').count()
        my_launch_flag = 1 if DeadlineNotification.objects.filter(end_deadline_time__lt=datetime.now(), work_id__state__in=['one', 'two'], initiate_or_not='0').count() and request.user == jcs_head_obj else 0
        overdue_process_flag = obj.count()
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "overdue_process_flag": overdue_process_flag,
                   "DailyList": DailyList, "pages": int(page), 'page_all_number': page_all_number, "views_range_start": 1, "views_range_end": 20,
                   "page_list": page_list, "totals": obj.count(), "OverdueFlag": OverdueFlag, "deadline_flag": deadline_flag, "my_launch_flag": my_launch_flag}
        return render(request, 'supervision_inspection/overdue_process.html', context)


class InitiateTheAccountability(View):
    def post(self, request):
        flow_id = request.POST.get("flow_id", "")                                   # 工作流程ID
        current_id = request.POST.get("current_id", "")
        accountability_recommendations = request.POST.get("accountability_recommendations", "")

        dead_obj = DeadlineNotification.objects.get(id=int(current_id))
        flow_obj = WorkSuperviseHandle.objects.get(id=int(flow_id))
        dead_obj.initiate_or_not = '1'
        dead_obj.state = "end"
        dead_obj.current_audit_users.clear()
        dead_obj.save()

        # 计数器
        count = 0
        # 当前日期
        appeal_end_time = datetime.today().date()
        while count < 5:
            # 增加一天
            appeal_end_time += timedelta(days=1)
            # 如果是工作日（周一到周五），则计数增加
            if appeal_end_time.weekday() < 5:  # 周一到周五的weekday值是0到4
                count += 1

        obj = InitiateAccountability.objects.create(state="one", apply_user=request.user, responsible_person=flow_obj.responsible_person, work_id=flow_obj,
                                                    accountability_recommendations=accountability_recommendations, dead_id=dead_obj, appeal_end_time=appeal_end_time)
        obj.current_audit_users.add(request.user.company.leaders_id)
        InitiateAccountabilityRecord.objects.create(parent_id=obj, node="one", audit_people=request.user.company.leaders_id)
        InitiateAccountabilityRecord.objects.create(parent_id=obj, node="two", audit_people=flow_obj.responsible_person)
        InitiateAccountabilityRecord.objects.create(parent_id=obj, node="three", audit_people=Company.objects.get(id=18).head_people)
        InitiateAccountabilityRecord.objects.create(parent_id=obj, node="four", audit_people=Company.objects.get(id=18).leaders_id)
        InitiateAccountabilityRecord.objects.create(parent_id=obj, node="five", audit_people=Company.objects.get(id=18).head_people)
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class SupervisionAndAccountability(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'supervision_inspection/supervision_and_accountability.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = InitiateAccountability.objects.filter(apply_user=request.user).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'title': obj.work_id.job_source,
                      'company': obj.work_id.company.name,
                      'responsible_person': obj.responsible_person.real_name,
                      'state': obj.get_str_state(),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      }
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class AccountabilityDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = InitiateAccountability.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.initiateaccountabilityrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.initiateaccountabilityrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = []
        RecordObj = obj.work_id.worksupervisehandlerecord_set.filter(~Q(state='unaudit')).order_by("-create_time")
        FeedbackList = []
        for i in RecordObj:
            FeedbackList.append({"name": i.audit_people.real_name, "time": i.update_time.strftime("%Y-%m-%d %H:%M"), "audit_note": '转审' if i.state== 'referee' and not i.audit_note else i.audit_note if i.audit_note else '同意', "file_path": i.file_path.replace(os.getcwd(), ""), 'state': '转审' if i.state == 'referee' else "拒绝" if i.state == 'draft' else "同意"})
        FeedbackList.append({"name": obj.work_id.apply_user.real_name, "time": obj.create_time.strftime("%Y-%m-%d %H:%M"), "audit_note": "创建工作", 'file_path': '', 'state': '创建'})
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list, "FeedbackList": FeedbackList, "appeal_flag": 'true' if datetime.now() < obj.appeal_end_time and obj.state == "two" else "false",
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'ten'] and request.user in obj.current_audit_users.all() else 'false',
                   'flow_dict': flow_dict, "suffix": obj.work_id.attachment_name.split(".")[-1], "attachment_name": obj.work_id.attachment_name,
                   'file_path': f'/static/supervision_inspection/attachment_first_level/{obj.work_id.fj_number}/{obj.work_id.attachment_name}'
                   }
        return render(request, 'supervision_inspection/accountability_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", "audit")  # draft 拒绝 audit 通过
        initiate_account = request.POST.get('initiate_account', '')
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "问责申请")
        except:
            pass
        obj = InitiateAccountability.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.initiateaccountabilityrecord_set.filter(node='one', state='unaudit').first()

            obj.appeal_end_time = datetime.today().date() + timedelta(days=5)
            if initiate_account == '0':
                next_audit_record = obj.initiateaccountabilityrecord_set.filter(node='three', state='unaudit').first()
                obj.initiateaccountabilityrecord_set.filter(state='unaudit').delete()
                InitiateAccountabilityRecord.objects.create(parent_id=obj, node="ten", audit_people=Company.objects.get(id=18).head_people)
                obj_state = 'ten'
            else:
                next_audit_record = obj.initiateaccountabilityrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            obj.current_audit_users.add(next_audit_record.audit_people)

        elif obj.state == 'two':
            whether_appeal = request.POST.get('whether_appeal', '')
            audit_record = obj.initiateaccountabilityrecord_set.filter(node='two', state='unaudit').first()
            next_audit_record = obj.initiateaccountabilityrecord_set.filter(node='three', state='unaudit').first()
            obj_state = 'three'
            obj.whether_appeal = whether_appeal
            obj.current_audit_users.add(next_audit_record.audit_people)

        elif obj.state == 'three':
            audit_record = obj.initiateaccountabilityrecord_set.filter(node='three', state='unaudit').first()
            next_audit_record = obj.initiateaccountabilityrecord_set.filter(node='four', state='unaudit').first()
            obj_state = 'four'
            obj.current_audit_users.add(next_audit_record.audit_people)

        elif obj.state == 'four':
            meeting = request.POST.get('meeting', '')
            obj.whether_meeting = meeting
            audit_record = obj.initiateaccountabilityrecord_set.filter(node='four', state='unaudit').first()
            if meeting == '1':
                next_audit_record = obj.initiateaccountabilityrecord_set.filter(node='five', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                obj_state = 'five'
            else:
                obj.initiateaccountabilityrecord_set.filter(state='unaudit').delete()
                supervision_office_obj = Company.objects.get(id=18).head_people
                InitiateAccountabilityRecord.objects.create(parent_id=obj, node="ten", audit_people=supervision_office_obj)
                obj.current_audit_users.add(supervision_office_obj)
                obj_state = 'ten'

        elif obj.state == 'ten':
            DelayDays = request.POST.get('DelayDays', '')
            delay_end = request.POST.get('delay_end', '')
            audit_record = obj.initiateaccountabilityrecord_set.filter(node='ten', state='unaudit').first()
            if delay_end == '1':
                end_time = datetime.today().date() + timedelta(days=int(DelayDays))
                audit_note = f"延期至{str(end_time).split(' ')[0]}"
                obj.work_id.state = "one"
                obj.work_id.end_time = str(end_time).split(' ')[0]
                WorkSuperviseHandleRecord.objects.create(parent_id=obj.work_id, state="audit", node="ten", audit_people=request.user, audit_note=f"延期至{str(end_time).split(' ')[0]}")
                WorkSuperviseHandleRecord.objects.filter(parent_id=obj.work_id, state="unaudit").delete()
                zgb_leader = Company.objects.get(id=4).head_people
                WorkSuperviseHandleRecord.objects.create(parent_id=obj.work_id, state='unaudit', node='one', audit_people=obj.work_id.responsible_person, audit_note='')
                WorkSuperviseHandleRecord.objects.create(parent_id=obj.work_id, state='unaudit', node='two', audit_people=obj.work_id.company.leaders_id, audit_note='')
                WorkSuperviseHandleRecord.objects.create(parent_id=obj.work_id, state='unaudit', node='three', audit_people=zgb_leader, audit_note='')
                WorkSuperviseHandleRecord.objects.create(parent_id=obj.work_id, state='unaudit', node='five', audit_people=obj.work_id.apply_user, audit_note='')
                obj.work_id.current_audit_users.add(obj.work_id.responsible_person,)
                obj.work_id.transfer_supervision_office = '0'
            else:
                obj.work_id.state = "end"
                obj.work_id.current_audit_users.clear()
            obj_state = 'end'
            obj.work_id.save()

        else:
            audit_record = obj.initiateaccountabilityrecord_set.filter(node='five', state='unaudit').first()
            if obj.whether_meeting == '0':
                DelayDays = request.POST.get('DelayDays', '')

                obj.dead_id.audit_users_already.add(request.user)
                obj.dead_id.current_audit_users.clear()
                obj.dead_id.state = "one"
                obj.dead_id.end_deadline_time = datetime.today().date() + timedelta(days=int(DelayDays))
                obj.dead_id.current_audit_users.add(obj.responsible_person)
                WorkSuperviseHandleRecord.objects.create(parent_id=obj.work_id, state="audit", node="three", audit_people=request.user,
                                                         audit_note=f"延期至{str(obj.dead_id.end_deadline_time).split(' ')[0]}")
                obj.dead_id.save()
            obj_state = 'end'

        obj.state = obj_state
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        returnDict = {'status': 'success', "code": 200, "message": "操作成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class PerformanceManagement(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        objs = PerformanceAllocation.objects.all()
        obj = ''
        if objs.count():
            obj = PerformanceAllocation.objects.filter(years=objs.last().years, month=objs.last().month)
        years_obj = PerformanceAllocation.objects.all().values("years").distinct()
        month_obj = PerformanceAllocation.objects.all().values("month").distinct()
        year_list = []
        for year in years_obj:
            year_list.append(year["years"])

        month_list = []
        for month in month_obj:
            month_list.append(month["month"])

        upload_flag = 'false'
        if request.user.company.id == 10:
            upload_flag = 'true'

        obj_count = DepartmentPerformanceAllocation.objects.filter(assignor=request.user, whether_allocate='0')
        share_flag = 'false'
        if obj_count.count():
            share_flag = 'true'
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "year_list": year_list,
                   "month_list": month_list, 'search_year': objs.last().years if objs.count() else datetime.now().year,
                   'search_month': objs.last().month if objs.count() else datetime.now().month,
                   'upload_flag': upload_flag, 'share_flag': share_flag}
        return render(request, 'supervision_inspection/performance_management.html', context)

class SwitchTables(View):
    def post(self, request):
        search_year = request.POST.get("search_year", "")
        search_month = request.POST.get("search_month", "")
        data_type = request.POST.get("data_type", "")

        if search_year:
            if data_type == 'a':
                data_html = SwitchData().SearchPerformanceAllocation(search_year, search_month)
            elif data_type == 'b':
                data_html = SwitchData().SearchPerformanceAllocationClinical(search_year, search_month)
            elif data_type == 'c':
                data_html = SwitchData().SearchPerformanceAllocationTalentReserve(search_year, search_month)
            elif data_type == 'd':
                data_html = SwitchData().SearchPerformanceAllocationOtherSingleItems(search_year, search_month)
            elif data_type == 'e':
                data_html = SwitchData().SearchPerformanceAllocationMedicalCommunity(search_year, search_month)
            elif data_type == 'f':
                data_html = SwitchData().SearchPerformanceAllocationOutpatientSpecialty(search_year, search_month)
            elif data_type == 'g':
                data_html = SwitchData().SearchPerformanceAllocationConsultationPerformance(search_year, search_month)
            elif data_type == 'h':
                data_html = SwitchData().SearchPerformanceAllocationNightShiftPerformance(search_year, search_month)
            elif data_type == 'i':
                data_html = SwitchData().SearchPerformanceAllocationDirectorPerformance(search_year, search_month)
            elif data_type == 'j':
                data_html = SwitchData().SearchPerformanceAllocationComprehensiveTargetPerformance(search_year, search_month, '1')
            elif data_type == 'k':
                data_html = SwitchData().SearchPerformanceAllocationComprehensiveTargetPerformance(search_year, search_month, '2')
            else:
                data_html = SwitchData().SearchPerformanceAllocationNewTalentReserve(search_year, search_month)
            returnDict = {'status': 'success', "code": 200, "message": "查询成功！", "data": data_html}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            returnDict = {'status': 'success', "code": 400, "message": "未查询到数据！", "data": ''}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class switch_tables(View):
    def post(self, request):
        search_year = request.POST.get("search_year", "")
        search_month = request.POST.get("search_month", "")
        department_code = request.POST.get("department_code", "")
        data_type = request.POST.get("data_type", "")

        if search_year:
            if data_type == 'a':
                data_html = SwitchDataCopy().SearchPerformanceAllocation(search_year, search_month, department_code)
            elif data_type == 'b':
                data_html = SwitchDataCopy().SearchPerformanceAllocationClinical(search_year, search_month, department_code)
            elif data_type == 'c':
                data_html = SwitchDataCopy().SearchPerformanceAllocationTalentReserve(search_year, search_month, department_code)
            elif data_type == 'd':
                data_html = SwitchDataCopy().SearchPerformanceAllocationOtherSingleItems(search_year, search_month, department_code)
            elif data_type == 'e':
                data_html = SwitchDataCopy().SearchPerformanceAllocationMedicalCommunity(search_year, search_month, department_code)
            elif data_type == 'f':
                data_html = SwitchDataCopy().SearchPerformanceAllocationOutpatientSpecialty(search_year, search_month, department_code)
            elif data_type == 'g':
                data_html = SwitchDataCopy().SearchPerformanceAllocationConsultationPerformance(search_year, search_month, department_code)
            elif data_type == 'h':
                data_html = SwitchDataCopy().SearchPerformanceAllocationNightShiftPerformance(search_year, search_month, department_code)
            elif data_type == 'i':
                data_html = SwitchDataCopy().SearchPerformanceAllocationDirectorPerformance(search_year, search_month, department_code)
            elif data_type == 'j':
                data_html = SwitchDataCopy().SearchPerformanceAllocationComprehensiveTargetPerformance(search_year, search_month, '1', department_code)
            elif data_type == 'k':
                data_html = SwitchDataCopy().SearchPerformanceAllocationComprehensiveTargetPerformance(search_year, search_month, '2', department_code)
            else:
                data_html = SwitchDataCopy().SearchPerformanceAllocationNewTalentReserve(search_year, search_month, department_code)
            returnDict = {'status': 'success', "code": 200, "message": "查询成功！", "data": data_html}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            returnDict = {'status': 'success', "code": 400, "message": "未查询到数据！", "data": ''}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DepartmentUploadsPerformance(View):
    def post(self, request):
        upload_type = request.POST.get("upload_type", "")
        performance_year = request.POST.get("performance_year", "")
        performance_month = request.POST.get("performance_month", "")
        files = request.FILES.get('file')

        wb = xlrd.open_workbook(filename=None, file_contents=files.read())
        dir_path = os.getcwd() + f'/media/performance_file/{uuid.uuid4()}'
        save_file_path = os.path.join(dir_path, files.name)
        print(save_file_path)
        if os.path.exists(save_file_path):
            os.remove(save_file_path)
        os.makedirs(dir_path)
        with open(save_file_path, 'w') as f:
            pass
        destination = open(save_file_path, 'wb+')  # 打开特定的文件进行二进制的写操作
        for chunk in files.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()
        if upload_type == "1":
            SheetName = wb.sheet_names()
            for names in SheetName:
                file_table = wb.sheet_by_name(names)
                file_table_rows = file_table.nrows
                if "正01表" in names:
                    SaveExcel().SavePerformanceAllocation(file_table_rows, performance_year, performance_month, file_table, request.user)
                elif "临床科室" in names:
                    SaveExcel().SavePerformanceAllocationClinical(file_table_rows, performance_year, performance_month, file_table, request.user)
                elif "人才储备绩效" in names:
                    SaveExcel().SavePerformanceAllocationTalentReserve(file_table_rows, performance_year, performance_month, file_table, request.user)
                elif "其他单项" in names:
                    SaveExcel().SavePerformanceAllocationOtherSingleItems(file_table_rows, performance_year, performance_month, file_table, request.user)
                elif "医共体专项" in names:
                    SaveExcel().SavePerformanceAllocationMedicalCommunity(file_table_rows, performance_year, performance_month, file_table, request.user)
                elif "门诊专项绩效" in names:
                    SaveExcel().SavePerformanceAllocationOutpatientSpecialty(file_table_rows, performance_year, performance_month, file_table, request.user)
                elif "会诊绩效" in names:
                    SaveExcel().SavePerformanceAllocationConsultationPerformance(file_table_rows, performance_year, performance_month, file_table, request.user)
                elif "夜班绩效" in names:
                    SaveExcel().SavePerformanceAllocationNightShiftPerformance(file_table_rows, performance_year, performance_month, file_table, request.user)
                elif "科主任管理绩效" in names:
                    SaveExcel().SavePerformanceAllocationDirectorPerformance(file_table_rows, performance_year, performance_month, file_table, request.user)
                elif "临床科室" in names:
                    SaveExcel().SavePerformanceAllocationComprehensiveTargetPerformance(file_table_rows, performance_year, performance_month, file_table, request.user, '1')
                elif "医技及其他" in names:
                    SaveExcel().SavePerformanceAllocationComprehensiveTargetPerformance(file_table_rows, performance_year, performance_month, file_table, request.user, '2')
                else:
                    SaveExcel().SavePerformanceAllocationNewTalentReserve(file_table_rows, performance_year, performance_month, file_table, request.user)

        returnDict = {'status': 'success', "code": 200, "message": "创建成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DepartmentPerformance(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        obj_count = DepartmentPerformanceAllocation.objects.filter(assignor=request.user, whether_allocate='0')
        share_flag, purview_flag, office_staff, workload_money, night_shift_performance_money, medical_community_money = 'false', 'false', [], 0, 0, 0
        if obj_count.count():
            share_flag = 'true'
            purview_flag = 'true'
            current_obj = PerformanceAllocation.objects.filter(years=obj_count.first().years, month=obj_count.first().month, department_code=obj_count.first().department_code)
            department_code = obj_count.first().department_code
            search_year = obj_count.first().years
            search_month = obj_count.first().month
            company_name = current_obj.first().department_name
            workload_money = current_obj.first().workload
            night_shift_performance_money = current_obj.first().night_shift_performance
            medical_community_money = current_obj.first().medical_community
            all_office_staff = User.objects.filter(company=request.user.company)
            serial = 1
            for staff in all_office_staff:
                create_obj = PerformanceAllocationHead.objects.filter(job_number=staff.job_number, years=obj_count.first().years,  month=obj_count.first().month)
                if create_obj.count():
                    office_staff.append({
                        'id': staff.id, 'real_name': create_obj.first().real_name, 'job_number': create_obj.first().job_number, 'company': create_obj.first().department_name,
                        'department_code': create_obj.first().department_code, 'serial': serial, 'duties': create_obj.first().duties, 'identity': create_obj.first().identity,
                        'bank_account': create_obj.first().bank_account, 'workload': create_obj.first().workload, 'night_shift_performance': create_obj.first().night_shift_performance,
                        'medical_community': create_obj.first().medical_community, 'total_salary': create_obj.first().total_salary, 'falg': 'true'
                    })
                else:
                    office_staff.append({
                        'id': staff.id, 'real_name': staff.real_name, 'job_number': staff.job_number, 'company': company_name, 'department_code': department_code, 'serial': serial,
                        'duties': '', 'identity': '', 'bank_account': '', 'workload': '', 'night_shift_performance': '', 'medical_community': '', 'total_salary': '', 'falg': 'true'
                    })
                serial += 1
        else:
            last_obj = DepartmentPerformanceAllocation.objects.filter(assignor=request.user, whether_allocate='1')
            if last_obj.count():
                purview_flag = 'true'
                current_obj = PerformanceAllocation.objects.filter(years=last_obj.last().years, month=last_obj.last().month, department_code=last_obj.last().department_code)
                department_code = last_obj.last().department_code
                search_year = last_obj.last().years
                search_month = last_obj.last().month

                create_obj = PerformanceAllocationHead.objects.filter(years=search_year, month=search_month)
                serial = 1
                for hh in create_obj:
                    office_staff.append({
                        'id': serial, 'real_name': hh.real_name, 'job_number': hh.job_number, 'company': hh.department_name,
                        'department_code': hh.department_code, 'serial': serial, 'duties': hh.duties, 'identity': hh.identity,
                        'bank_account': hh.bank_account, 'workload': hh.workload, 'night_shift_performance': hh.night_shift_performance,
                        'medical_community': hh.medical_community, 'total_salary': hh.total_salary, 'falg': 'false'
                    })
                    serial += 1
            else:
                current_obj = {}
                department_code = ''
                search_year = ''
                search_month = ''

        years_obj = PerformanceAllocation.objects.all().values("years").distinct()
        month_obj = PerformanceAllocation.objects.all().values("month").distinct()
        year_list = []
        for year in years_obj:
            year_list.append(year["years"])

        month_list = []
        for month in month_obj:
            month_list.append(month["month"])
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'share_flag': share_flag, 'current_obj': current_obj, 'year_list': year_list,
                   'month_list': month_list, 'search_year': search_year, 'search_month': search_month, 'department_code': department_code, 'purview_flag': purview_flag, 'office_staff': office_staff,
                   'workload_money': workload_money, 'night_shift_performance_money': night_shift_performance_money, 'medical_community_money': medical_community_money}
        return render(request, 'supervision_inspection/department_performance.html', context)

class PerformanceDataSave(View):
    def post(self, request):
        TableArrayList = request.POST.get("TableArrayList", '')
        summit_type = request.POST.get("summit_type", '')
        search_year = request.POST.get("search_year", '')
        search_month = request.POST.get("search_month", '')
        table_array_list = json.loads(TableArrayList)
        for array_data in table_array_list:
            already_data = PerformanceAllocationHead.objects.filter(job_number=array_data[4], years=search_year,  month=search_month)
            if already_data.count():
                for jj in already_data:
                    jj.department_code = array_data[0]
                    jj.department_name = array_data[1]
                    jj.duties = array_data[2]
                    jj.identity = array_data[3]
                    jj.job_number = array_data[4]
                    jj.real_name = array_data[5]
                    jj.bank_account = array_data[6]
                    jj.workload = array_data[7]
                    jj.night_shift_performance = array_data[8]
                    jj.medical_community = array_data[9]
                    jj.total_salary = array_data[10]
                    if summit_type != "save":
                        jj.state = 1
                    jj.save()
            else:
                obj = PerformanceAllocationHead.objects.create(apply_user=request.user, department_code=array_data[0], department_name=array_data[1], duties=array_data[2], years=search_year,
                                                 identity=array_data[3], job_number=array_data[4], real_name=array_data[5], bank_account=array_data[6], month=search_month,
                                                 workload=array_data[7], night_shift_performance=array_data[8], medical_community=array_data[9], total_salary=array_data[10])
                if summit_type != "save":
                    obj.state = '1'
                    obj.save()
        if summit_type != "save":
            obj_list = DepartmentPerformanceAllocation.objects.filter(assignor=request.user, years=search_year, month=search_month)
            for kk in obj_list:
                kk.whether_allocate = '1'
                kk.save()
        returnDict = {'code': 200, 'message': "操作成功！", 'data': []}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SuperviseCompleted(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        search_dep = request.GET.get("search_dep", "")
        search_year = request.GET.get("search_year", "")
        search_month = request.GET.get("search_month", "")
        search_key = request.GET.get("search_key", "")

        upload_flag = 'false'
        if request.user.company.id == 10:
            upload_flag = 'true'

        years_obj = PerformanceAllocationHead.objects.filter(state='1').values("years").distinct()
        month_obj = PerformanceAllocationHead.objects.filter(state='1').values("month").distinct()
        year_list, month_list, dep_list, set_list = [], [], [], []
        for year in years_obj:
            year_list.append(year["years"])
        for month in month_obj:
            month_list.append(month["month"])

        obj_count = PerformanceAllocationHead.objects.filter(state='1')
        obj = ""
        if obj_count.count():
            if search_year and search_month and search_dep:
                obj = PerformanceAllocationHead.objects.filter(Q(department_code__contains=search_key) | Q(duties__contains=search_key) | Q(identity__contains=search_key) | Q(real_name__contains=search_key), state='1', years=search_year, month=search_month, department_code=search_dep)
            elif search_year and search_month and not search_dep:
                obj = PerformanceAllocationHead.objects.filter(Q(department_code__contains=search_key) | Q(duties__contains=search_key) | Q(identity__contains=search_key) | Q(real_name__contains=search_key), state='1', years=search_year, month=search_month)
            elif search_year and not search_month and search_dep:
                obj = PerformanceAllocationHead.objects.filter(Q(department_code__contains=search_key) | Q(duties__contains=search_key) | Q(identity__contains=search_key) | Q(real_name__contains=search_key), state='1', years=search_year, department_code=search_dep)
            elif not search_year and search_month and search_dep:
                obj = PerformanceAllocationHead.objects.filter(Q(department_code__contains=search_key) | Q(duties__contains=search_key) | Q(identity__contains=search_key) | Q(real_name__contains=search_key), state='1', month=search_month, department_code=search_dep)
            elif search_year and not search_month and not search_dep:
                obj = PerformanceAllocationHead.objects.filter(Q(department_code__contains=search_key) | Q(duties__contains=search_key) | Q(identity__contains=search_key) | Q(real_name__contains=search_key), state='1', years=search_year)
            elif not search_year and search_month and not search_dep:
                obj = PerformanceAllocationHead.objects.filter(Q(department_code__contains=search_key) | Q(duties__contains=search_key) | Q(identity__contains=search_key) | Q(real_name__contains=search_key), state='1', month=search_month)
            elif not search_year and not search_month and search_dep:
                obj = PerformanceAllocationHead.objects.filter(Q(department_code__contains=search_key) | Q(duties__contains=search_key) | Q(identity__contains=search_key) | Q(real_name__contains=search_key), state='1', department_code=search_dep)
            else:
                obj = PerformanceAllocationHead.objects.filter(Q(department_code__contains=search_key) | Q(duties__contains=search_key) | Q(identity__contains=search_key) | Q(real_name__contains=search_key), state='1', years=obj_count.last().years, month=obj_count.last().month)

            dep_list_obj = PerformanceAllocationHead.objects.filter(state='1', years=obj_count.last().years, month=obj_count.last().month)
            for dep in dep_list_obj:
                if dep.department_name not in set_list:
                    set_list.append(dep.department_name)
                    dep_list.append({"name": dep.department_name, 'code': dep.department_code})
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "upload_flag": upload_flag, 'year_list': year_list,
                   'month_list': month_list, 'obj_count': 'true' if obj_count.count() else 'false', 'obj': obj, 'dep_list': dep_list, 'SearchDep': search_dep, 'SearchYear': search_year,
                   'SearchMonth': search_month, 'SearchKey': search_key}
        return render(request, 'supervision_inspection/supervise_completed.html', context)

    def post(self, request):
        upload_year = request.POST.get("upload_year", '')
        upload_month = request.POST.get("upload_month", '')
        myFiles = request.FILES.get("file", "")
        # file_path = os.path.join(os.getcwd(), f'static/supervision_inspection/director_performance')
        # if not os.path.exists(file_path):
        #     os.mkdir(file_path)
        # with open(os.path.join(file_path, myFiles.name), "wb") as F:
        #     for i in myFiles.chunks():
        #         F.write(i)
        wb = xlrd.open_workbook(filename=None, file_contents=myFiles.read())
        file_table = wb.sheet_by_index(0)
        file_table_rows = file_table.nrows
        for row_index in range(1, file_table_rows):
            if file_table.cell(row_index, 0).value:
                try:
                    obj = PerformanceAllocationHead.objects.get(job_number=str(int(file_table.cell(row_index, 1).value)), years=upload_year, month=upload_month)
                    print(obj.id)
                    obj.managing_performance = file_table.cell(row_index, 2).value
                    obj.consultation_performance = file_table.cell(row_index, 3).value
                    obj.special_performance = file_table.cell(row_index, 4).value
                    obj.individual_performance = file_table.cell(row_index, 5).value
                    obj.reserve_performance = file_table.cell(row_index, 6).value
                    obj.save()
                except:
                    pass
        returnDict = {'code': 200, 'message': '上传成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ShiftChangeList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'supervision_inspection/shift_change_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = ShiftAdjustment.objects.filter(apply_user=request.user).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'shift_change_reason': obj.shift_change_reason,
                      'shift_change_personnel': obj.shift_change_personnel.real_name if obj.shift_change_personnel else "",
                      'shift_change_telephone': obj.shift_change_telephone,
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='shift_change_draft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='shift_change_detail.html?id={obj.id}'>查看</a> | <a href='shift_change_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state != 'draft'
                      else f"<a href='shift_change_detail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='shift_change_detail.html?id={obj.id}'>查看</a>",
                      'state': obj.get_state_str()}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ShiftChangeIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "telephone": request.user.mobile, "uuid": uuid.uuid4()}
        return render(request, 'supervision_inspection/shift_change_index.html', context)

    def post(self, request):
        flow_id = request.POST.get("flow_id", '')
        shift_change_reason = request.POST.get("shift_change_reason", '')
        old_duty_time = request.POST.get("old_duty_time", '')
        shift_change_personnel = request.POST.get("shift_change_personnel", '')
        shift_change_telephone = request.POST.get("shift_change_telephone", '')
        note = request.POST.get("note", '')
        fj_number = request.POST.get("uuid", '')
        ShiftChangePersonnel = User.objects.get(job_number=re.findall('\((.*?)\)', shift_change_personnel)[0])
        if flow_id:
            obj = ShiftAdjustment.objects.get(id=int(flow_id))
            obj.old_duty_time = old_duty_time
            obj.shift_change_personnel = ShiftChangePersonnel
            obj.shift_change_telephone = shift_change_telephone
            obj.shift_change_reason = shift_change_reason
            obj.note = note

            obj.current_audit_users.clear()
            obj.shiftadjustmentrecord_set.filter(state="unaudit").delete()
            obj.save()
            message = "修改成功！"
        else:
            obj = ShiftAdjustment.objects.create(apply_user=request.user, telephone=request.user.mobile, old_duty_time=old_duty_time,
                                            shift_change_personnel=ShiftChangePersonnel, shift_change_telephone=shift_change_telephone,
                                            shift_change_reason=shift_change_reason, note=note, fj_number=fj_number)
            message = "创建成功！"

        ShiftAdjustmentRecord.objects.create(parent_id=obj, node="one", audit_people=ShiftChangePersonnel, audit_note="", state="unaudit")
        obj.current_audit_users.add(ShiftChangePersonnel)
        obj.state = "one"

        two_step = request.user.company.head_people  # 科主任
        if request.user != two_step:
            ShiftAdjustmentRecord.objects.create(parent_id=obj, node="two", audit_people=two_step, audit_note="", state="unaudit")

        ShiftAdjustmentRecord.objects.create(parent_id=obj, node="three", audit_people=request.user.company.leaders_id, audit_note="", state="unaudit")

        if not request.user.company.is_functional:
            if "护理" not in request.user.role:
                four_step = Company.objects.get(id=15).head_people
                ShiftAdjustmentRecord.objects.create(parent_id=obj, node="four", audit_people=four_step, audit_note="", state="unaudit")
            else:
                four_step = Company.objects.get(id=13).head_people
                ShiftAdjustmentRecord.objects.create(parent_id=obj, node="four", audit_people=four_step, audit_note="", state="unaudit")

        OfficeObj = Staffing.objects.get(station="换班受理人").post_personnel.all()
        for office in OfficeObj:
            ShiftAdjustmentRecord.objects.create(parent_id=obj, node="five", audit_people=office, audit_note="", state="unaudit")

        obj.save()
        returnDict = {'code': 200, 'message': message}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ShiftChangeDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ShiftAdjustment.objects.get(id=int(flow_id))
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "revise": revise, "file_list": file_list}
        return render(request, 'supervision_inspection/shift_change_draft.html', context)

    def post(self, request):
        flow_id = request.POST.get("flow_id", '')
        shift_change_reason = request.POST.get("shift_change_reason", '')
        old_duty_time = request.POST.get("old_duty_time", '')
        shift_change_personnel = request.POST.get("shift_change_personnel", '')
        shift_change_telephone = request.POST.get("shift_change_telephone", '')
        note = request.POST.get("note", '')
        fj_number = request.POST.get("uuid", '')
        ShiftChangePersonnel = None
        if shift_change_personnel:
            ShiftChangePersonnel = User.objects.get(job_number=re.findall('\((.*?)\)', shift_change_personnel)[0])
        if flow_id:
            obj = ShiftAdjustment.objects.get(id=int(flow_id))
            obj.old_duty_time = old_duty_time
            obj.shift_change_personnel = ShiftChangePersonnel
            obj.shift_change_telephone = shift_change_telephone
            obj.shift_change_reason = shift_change_reason
            obj.note = note

            obj.current_audit_users.clear()
            obj.shiftadjustmentrecord_set.filter(state="unaudit").delete()
            obj.save()
            message = "修改成功！"
        else:
            obj = ShiftAdjustment.objects.create(apply_user=request.user, telephone=request.user.mobile, old_duty_time=old_duty_time,
                                                 shift_change_personnel=ShiftChangePersonnel, shift_change_telephone=shift_change_telephone,
                                                 shift_change_reason=shift_change_reason, note=note, fj_number=fj_number)
            message = "创建成功！"
        obj.state = "draft"
        obj.save()
        returnDict = {'code': 200, 'message': message}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ShiftChangeDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ShiftAdjustment.objects.get(id=int(flow_id))
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.shiftadjustmentrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.shiftadjustmentrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "revise": revise, "file_list": file_list, "audit_dic": audit_dic, "flow_dict": flow_dict,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'refuse'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'supervision_inspection/shift_change_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "调班申请")
        except:
            pass
        obj = ShiftAdjustment.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.remove(request.user)
        if obj.state == 'one':
            audit_record = obj.shiftadjustmentrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.shiftadjustmentrecord_set.filter(node='one', state='unaudit').count() == 1:
                    if obj.shiftadjustmentrecord_set.filter(node='two', state='unaudit').count():
                        next_audit_record = obj.shiftadjustmentrecord_set.filter(node='two', state='unaudit')
                        obj_state = 'two'
                    elif obj.shiftadjustmentrecord_set.filter(node='three', state='unaudit').count():
                        next_audit_record = obj.shiftadjustmentrecord_set.filter(node='three', state='unaudit')
                        obj_state = 'three'
                    elif obj.shiftadjustmentrecord_set.filter(node='four', state='unaudit').count():
                        next_audit_record = obj.shiftadjustmentrecord_set.filter(node='four', state='unaudit')
                        obj_state = 'four'
                    else:
                        next_audit_record = obj.shiftadjustmentrecord_set.filter(node='five', state='unaudit')
                        obj_state = 'five'

                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                else:
                    obj_state = 'one'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.shiftadjustmentrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.shiftadjustmentrecord_set.filter(node='two', state='unaudit').count() == 1:
                    if obj.shiftadjustmentrecord_set.filter(node='three', state='unaudit').count():
                        next_audit_record = obj.shiftadjustmentrecord_set.filter(node='three', state='unaudit')
                        obj_state = 'three'
                    elif obj.shiftadjustmentrecord_set.filter(node='four', state='unaudit').count():
                        next_audit_record = obj.shiftadjustmentrecord_set.filter(node='four', state='unaudit')
                        obj_state = 'four'
                    else:
                        next_audit_record = obj.shiftadjustmentrecord_set.filter(node='five', state='unaudit')
                        obj_state = 'five'

                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                else:
                    obj_state = 'two'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.shiftadjustmentrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.shiftadjustmentrecord_set.filter(node='three', state='unaudit').count() == 1:
                    if obj.shiftadjustmentrecord_set.filter(node='four', state='unaudit').count():
                        next_audit_record = obj.shiftadjustmentrecord_set.filter(node='four', state='unaudit')
                        obj_state = 'four'
                    else:
                        next_audit_record = obj.shiftadjustmentrecord_set.filter(node='five', state='unaudit')
                        obj_state = 'five'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                else:
                    obj_state = 'two'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.shiftadjustmentrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.shiftadjustmentrecord_set.filter(node='four', state='unaudit').count() == 1:
                    next_audit_record = obj.shiftadjustmentrecord_set.filter(node='five', state='unaudit')
                    obj_state = 'five'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                else:
                    obj_state = 'four'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.shiftadjustmentrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.shiftadjustmentrecord_set.filter(node='five', state='unaudit').count() == 1:
                    obj_state = 'end'
                else:
                    obj_state = 'five'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ShiftChangeOperation(View):
    def post(self, request):
        types = request.POST.get("types", "")
        flow_id = request.POST.get("id", "")
        obj = ShiftAdjustment.objects.get(id=int(flow_id))
        if types == "delete":
            obj.current_audit_users.clear()
            obj.audit_users_already.clear()
            obj.shiftadjustmentrecord_set.all().delete()
            obj.delete()
        else:
            obj.current_audit_users.clear()
            obj.state = "stop"
            obj.save()
        returnDict = {'status': 'success', "code": 200, "message": "操作成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")